A while back I wrote a blog post regarding this topic. In that post I explain that it is safe to use a return statement inside a using block, because the using block will handle the disposing of the defined IDisposable object. This is one truly great ability of the IDisposable interface. It makes it very important to use in my opinion. The using block in combination is very nice, because it handles the disposal for you.
One of my commenter on that post asked me if I was certain that the return statement was safe. He asked this because he couldn't find it in the documents. He also asked me if I had any code showing that this behavior works as I claim it does. I quickly wrote this simple little piece of code which works to demonstrate this behavior.
In my example I have a few things. I have a class which implements IDisposable and all it does to dispose is to write to the console. I then wrote 3 methods which each create and instance of this class in a using statement. One class is normal; it returns after the using statement is complete. The other two end abruptly. One of them returns from within the using statement, and the other throws an exception within the using statement.
class Program { static void Main(string[] args) { Console.WriteLine("Application Starting\n"); Console.WriteLine("Before normal method"); NormalMethod(); Console.WriteLine("After normal method\n"); Console.WriteLine("Before return method"); ReturnFromMethod(); Console.WriteLine("After return method\n"); Console.WriteLine("Before Throw method"); try { ThrowFromMethod(); } catch (Exception ex) { Console.WriteLine("Caught the Exception: " + ex.Message); } Console.WriteLine("After Throw method\n"); Console.WriteLine("Application Ending"); } private static void NormalMethod() { using (MyDisposable myDisposable = new MyDisposable()) { // do nothing } return; } private static void ThrowFromMethod() { using (MyDisposable myDisposable = new MyDisposable()) { throw new Exception("This is the exception"); } } private static void ReturnFromMethod() { using (MyDisposable myDisposable = new MyDisposable()) { return; } Console.WriteLine("DO NOT WRITE THIS!!!"); return; } class MyDisposable : IDisposable { #region IDisposable Members public void Dispose() { Console.WriteLine("I am disposing!"); } #endregion } }
This code returns the following result. In this screen shot you should notice that each time it calls the dispose method of the MyDisposable object.
Give the code a shot in a console application, and you will see that the using statement cleans up disposable objects pretty nicely.
Download this sample code as a small C# console application here.
I hope you enjoyed this post. I would also like to thank Lambros for the good comment. I hope to get more feedback from you in the future.
Comments