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");
 writer.WriteLine("First line");
finally {
 if(writer != null)

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.

Anonymous methods

btnSave.Click += new EventHandler (btnSave_Click);

Have you seen this piece of code? Yes definitely I guess everyone knows this and aware why we use it. So when I use the code like above I need to implement the method btnSave_Click

If you have started using .net 2.0 or above you can also do this using anonymous method which is very simpler to use as below

btnSave.Click += delegate(object sender, EventArgs e)
MessageBox.Show("Data has been saved successfully");

This piece is called Anonymous method which allows declaration of inline methods without specifying the method names. It uses delegates and it is very useful when we have short code.