What is the purpose of the Using block in C#? How is it different from a local variable?
What is the purpose of the Using block in C#? How is it different
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the type implements IDisposable, it automatically disposes that type.
Given:
These are equivalent:
The second is easier to read and maintain.
Since C# 8 there is a new syntax for
usingthat may make for more readable code:It doesn’t have a
{ }block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:And have this: