Friday, March 26, 2010

Using Block on C#

Everyone is very familiar with using statement which is used as defining statement to include namespaces in your C# code.


There is one other place where we can use “using” block and you should be very clear with the using which I mentioned above and the using blocks. Let’s take a look at what is using block and what is the advantage of using them on our code.


First of all, when we use any object we need to dispose it once we are done with that object. This can be done more easily with using blocks.


using (TextWriter writer = File.CreateText("applog.txt"))
{
writer.WriteLine("First line");
}


This code is as good as below code

TextWriter writer = File.CreateText("applog.txt");
try{
 writer.WriteLine("First line");
}
finally {
 if(writer != null)
 writer.Dispose();
}


You can also use your objects with using block but one of the point we need to keep in mind is that, the object that you instantiate should implement System.IDisposable interface. And the objects can be used as local objects in the method in which objects are created.

No comments:

Post a Comment