This question already has an answer here:
- What are the uses of “using” in C# 29 answers
What is the purpose of the Using block in C#? How is it different from a local variable?
This question already has an answer here:
What is the purpose of the Using block in C#? How is it different from a local variable?
From MSDN:
In other words, the
using
statement tells .NET to release the object specified in theusing
block once it is no longer needed.The using statement is used to work with an object in C# that implements the
IDisposable
interface.The
IDisposable
interface has one public method calledDispose
that is used to dispose of the object. When we use the using statement, we don't need to explicitly dispose of the object in the code, the using statement takes care of it.When we use the above block, internally the code is generated like this:
For more details read: Understanding the 'using' statement in C#.
If the type implements IDisposable, it automatically disposes it.
Given:
These are equivalent:
The second is easier to read and maintain.