Note : This post is first published on June-2015 in my previous blog Techkindle. Moving the content to here.
Using block/statement is used to free unmanaged resources.
Using statement is translated to three parts,
This resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
this code gets translated to
Objects that implement IDisposable can be used in a using statement. Calling Dispose() explicitly (or implicitly via a using statement) can have performance benefits.
“Code that is using a resource can call Dispose() to indicate that the resource is no longer needed. If Dispose() is not called, then automatic disposal eventually occurs as a consequence of garbage collection.” - MSDN
In the below code we can observe the following points,
- If we use ‘using’ block along a Customer type, it give a compiler error, saying that “type used in a using statement must be implicitly convertible to ‘System.IDisposable’”.
- Same if use with Student type, it does not give any error, because it implements System.IDisposable interface.
Happy Coding :)