What is the C# Using block and why should I use it?
If the type implements IDisposable, it automatically disposes that type.
Given:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
These are equivalent:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
The second is easier to read and maintain.
Using
calls Dispose()
after the using
-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:
using (MyClass mine = new MyClass())
{
mine.Action();
}
would do the same as:
MyClass mine = new MyClass();
try
{
mine.Action();
}
finally
{
if (mine != null)
mine.Dispose();
}
Using using
is way shorter and easier to read.
From MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
In other words, the using
statement tells .NET to release the object specified in the using
block once it is no longer needed.