What are the uses of “using” in C#?

后端 未结 29 2984
有刺的猬
有刺的猬 2020-11-21 07:31

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of

29条回答
  •  Happy的楠姐
    2020-11-21 07:45

    Things like this:

    using (var conn = new SqlConnection("connection string"))
    {
       conn.Open();
    
        // Execute SQL statement here on the connection you created
    }
    

    This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.

提交回复
热议问题