Saturday, January 21, 2012

The using Statement

I wanted to have a better understanding on when to use the "using" statement and why is was recommended and actually enforced in some cases. There's a lot of documentation and discussion on the subject, but wanted to share a quick brief to help you out and record it on my blog journal. Here it is:

The using statement provides a convenient syntax that ensures the correct use of IDisposable objects. This means that by making use of the "using" statement properly, you are making sure that objects are correctly disposed. Now wait a minute, C# manages the garbage collection for me, and should actually dispose the objects correctly without requiring any extra code from me, right?

Well, it turns out that we use unmanaged resources in our code. And that is why the "using" statement is important to make sure that those unmanaged resources are disposed correctly once they are not in scope any more. File and Font are examples of unmanaged resources.

Here is the rule and the explanation:

"When you use an IDisposable object, you should declare and instantiate it in a using statement.
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned."

Here is a sample with the "using" statement:

Here is the proper equivalent without the "using" statement

I'll  be posting more samples along the way, hopefully sharing more code and samples that are useful for our every day tasks.Cheers!


  1. The code did help me! thanks and appreciate the simple logic! Sample Statements

    1. Hey Lisa, glad I could help. Thanks for stopping by and leaving your comment.