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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Data; | |
namespace UsingTest | |
{ | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Compiler error – "type used in a using statement must be implicitly convertible to 'System.IDisposable'". | |
using (Customer objCustomer = new Customer("Kevin")) | |
{ | |
Console.WriteLine(objCustomer.ToString()); | |
Console.ReadKey(); | |
} | |
using (Student objStudent = new Student("Kevin")) | |
{ | |
Console.WriteLine(objStudent.ToString()); | |
Console.ReadKey(); | |
} | |
} | |
} | |
public class Customer | |
{ | |
public string Name { get; set; } | |
public Customer(string name) | |
{ | |
this.Name = name; | |
} | |
public override string ToString() | |
{ | |
return Name; | |
} | |
} | |
public class Student :IDisposable | |
{ | |
public string Name { get; set; } | |
public Student(string name) | |
{ | |
this.Name = name; | |
} | |
public override string ToString() | |
{ | |
return Name; | |
} | |
void Dispose() | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} |
Happy Learning 🙂