Tuesday, October 16, 2007

Using using

Submit this story to DotNetKicks

When writing code that makes use of alot of unmanaged memory resources, all objects should be disposed of before exiting methods and such. The keyword using is often forgotten, and also sometimes seen as messy. example:

using (Bitmap bitmap1 = new Bitmap(100, 100))
{
Console.WriteLine("Width:{0}, Height:{1}", bitmap1.Width, bitmap1.Height);
}

should basically be the same as

Bitmap bitmap1 = new Bitmap(100, 100)
Console.WriteLine("Width:{0}, Height:{1}", bitmap1.Width, bitmap1.Height);
bitmap1.Dispose();

shouldn't it?
No, not really... The using-clause does a little more than this. Actually, my using-example is equivalent to the following block of code.

Bitmap bitmap1 = new Bitmap(100, 100);
try
{
Console.WriteLine("Width:{0}, Height:{1}", bitmap1.Width, Bitmap1.Height);
}
finally
{
if (bitmap1 != null)
{
bitmap1.Dispose();
}
}
Console.ReadLine();


Imagine writing nested using-clauses, and try writing the expanded code for that :)
Using using really cleans up your code, and your memory. So use it!


Edit: Oh, as Stian commented. Using should be used for all objects that implements the IDisposable interface. But remember - if you plan on implementing this interface on your own classes, you need to make sure it fully implements all the necessary methods for cleaning up. Otherwise it will all be to waste :)

3 comments:

Stian Sveen said...

also good for sql stuff :) especially using ( SqlConnection ... ) {...}

F Quednau said...

using is fantastic!
Don't forget, you can also nest it:
using (Foo foo = new Foo())
using (Bar bar = new Bar(foo)) {
Console.WriteLine("Working with foo & bar");
}
They get disposed from bottom to top.
Also nice to do patterns like a progressbar or a timer..
using (ProgressBar pb = new Progressbar()) {
//blabla
}

I love it!

Yngve B. Nilsen said...

Yes! Very good point, and in cases like for instance SQLConnection, and then perhaps a SQLCommand, nesting using is almost a must.

Glad you like it :)