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?
Using
callsDispose()
after theusing
-block is left, even if the code throws an exception.So you usually use
using
for classes that require cleaning up after them, like IO.So, this using block:
would do the same as:
Using
using
is way shorter and easier to read.It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.
Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.
is equivalent to
The using statement obtains one or more resources, executes a statement, and then disposes of the resource.
Also take note that the object instantiated via
using
is read-only within the using block. Refer to the official C# reference here.