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

后端 未结 5 1568
执念已碎
执念已碎 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 08:50

    Declaring the variable inside the using statement's control expression limits the scope of the variable to inside the using statement. In your second example the variable cmd can continue to be used after the using statement (when it will have been disposed).

    Generally it is recommended to only use a variable for one purpose, limiting its scope allows another command with the same name later in scope (maybe in another using expression). Perhaps more importantly it tells a reader of your code (and maintenance takes more effort than initial writing) that cmd is not used beyond the using statement: your code is a little bit more understandable.

提交回复
热议问题