Can the C# using statement be written without the curly braces?

后端 未结 8 1031
陌清茗
陌清茗 2021-02-04 23:49

I was browsing a coworkers c# code today and found the following:

    using (MemoryStream data1 = new MemoryStream())
    using (MemoryStream data2 = new MemoryS         


        
相关标签:
8条回答
  • 2021-02-05 00:19

    From C# 8 you can also use this syntax without any braces:

    using var foo = new Foo();
    var bar = foo.Bar();
    

    foo will then be disposed at end of its scope (usually at the end of a method) - so be mindful where & when to use.

    Reference - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#example

    0 讨论(0)
  • 2021-02-05 00:32

    This is viable but risky, because if somebody later decides they want to do something to data1 before other stuff happens to it, they might place it right after the data1's using, which would take it out of the entire scope of data2's using. This would likely break compilation but still is a risky and pointless syntax shortcut..

    0 讨论(0)
提交回复
热议问题