Note : This post is first published on June-2015 in my previous blog Techkindle. Moving the content here.
using
Using block/statement is used to free unmanaged resources.
Using statement is translated to three parts,
- Acquisition
- Usage
- Disposal
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.
using (MemoryStream objStream = new MemoryStream()) { objStream.WriteTo(Response.OutputStream); }
this code gets translated to
MemoryStream objStream = new MemoryStream(); try { objStream.WriteTo(Response.OutputStream); } finally { if(objStream !=null) ((IDisposable)objStream).Dispose(); }
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.
Sample code
Happy Learning 🙂