Ferozeh dot Com
Expert advice on tech interviews !
about ferozeh

Ferozeh

Similar Questions


big table deletion SQL


cons of GC


finalize dispose close

Question

Difficulty Level: 2

  • Why do we use the C# using statement ?

Solution

Explanation Quality:4

Note that you can use the C# using statement only with types that implement the IDisposable interface. Say you are using a type that implements the IDispoable interface and after you are done using it, you would like to dispose it. your code would resemble much like below

myType.DoSomeWork();
myType.Dispose();

The problem with the above pseudocode is that the function DoSomeWork can throw an exception and dispose might never get called which may result in leak of memory. Therefor the best practise is to write the same code as follows

try{
  myType.DoSomeWork();
}
finally{
  myType.Dispose();
}

Putting the dispose function in the finally block ensures that the dispose method is called irrespective of any exceptions that might occur. For simplicity purposes you can achieve the same effect using the using C# statement as follows.

using(myType=new MyType()){
myType.DoSomeWork();
}

The compiler will automatically insert the try and finally blocks for you. Note you don't need to explicity call the Dispose method now, the compiler does that for you.

void WithoutUsingStatement() {

FileStream fs = new FileStream("exampleFile.txt", FileMode.Create);
byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("This is a test");

//The write method can throw exception say there's not enough
//memory on the hard disk
fs.Write(bytesToWrite, 0, bytesToWrite.Count());

//This statement will never get called if the exception is thrown
//by the previous statement
fs.Dispose();

}
void WithUsingStatement() {

byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("This is a test");
//Note the code is cleaner now and the dispose method is called by
//the CLR itself and we need not worry about it even if exceptions
//are thrown.
using (FileStream fs = new FileStream("exampleFile.txt", FileMode.Create))
{
  fs.Write(bytesToWrite, 0, bytesToWrite.Count());
}

}



Previous Next