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

后端 未结 8 1207
陌清茗
陌清茗 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:12

    Exactly what he said. The code above is exactly the same as writing:

    using (MemoryStream data1 = new MemoryStream()) 
    {
        using (MemoryStream data2 = new MemoryStream())
        {
            // Lots of code
        }
    }
    

    You can omit the curly braces after an if/else/for/while/using/etc statement as long as there is only one command within the statement. Examples:

    // Equivalent!
    if (x==6) 
        str = "x is 6";
    
    if(x == 6) {
        str = "x is 6";
    }
    
    // Equivalent!
    for (int x = 0; x < 10; ++x) z.doStuff();
    
    for (int x = 0; x < 10; ++x) {
        z.doStuff();
    }
    
    // NOT Equivalent! (The first one ONLY wraps the p = "bob";!)
    if (x == 5) 
    p = "bob";
    z.doStuff();
    
    if (x == 5) {
       p = "bob";
       z.doStuff();
    }
    

提交回复
热议问题