Can an object be declared above a using statement instead of in the brackets

后端 未结 5 1536
执念已碎
执念已碎 2021-01-17 08:23

Most of the examples of the using statement in C# declare the object inside the brackets like this:

using (SqlCommand cmd = new SqlCommand(\"SELECT * FROM Cu         


        
5条回答
  •  清酒与你
    2021-01-17 09:00

    Yes, that is valid - the object will still be disposed in the same manner, ie, at the end and if execution flow tries to leave the block (return / exception).

    However if you try to use it again after the using, it will have been disposed, so you cannot know if that instance is safe to continue using as dispose doesn't have to reset the object state. Also if an exception occurs during construction, it will not have hit the using block.

    I'd declare and initialize the variable inside the statement to define its scope. Chances are very good you won't need it outside the scope if you are using a using anyway.

    MemoryStream ms = new MemoryStream(); // Initialisation not compiled into the using.
    
    using (ms) { } 
    
    int i = ms.ReadByte(); // Will fail on closed stream.
    

    Below is valid, but somewhat unnecessary in most cases:

    MemoryStream ms = null;
    
    using (ms = new MemoryStream())
    { }
    
    // Do not continue to use ms unless re-initializing.
    

提交回复
热议问题