Thursday May 5th

Wednesday May 4th

Using using

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 :)


Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network