Brendan Enrick's Blog

Daily Software Development.


Returning From Inside a Using Statement

by Brendan Enrick Friday, November 21 2008 23:59

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.

 UsingStatementReturn

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.

Tagged as: ,

Comments

11/22/2008 4:27:54 AM #

I think the above resolves that issue. Nice to talk with you.


Regards,


Lambros


12/17/2008 10:56:31 AM #

I am somewhat partial to a few of the posts from my previous blog. For some of these posts, I just like the post, some the content about which the post was written, and some were just popular posts. Installing SQL Server Management Studio with SQL Server


5/6/2009 2:19:51 PM #

Pingback from Return Within a C# Using Statement : Brendan Enrick's Blog


5/19/2009 9:18:01 AM #

Pingback from Return Within a C# Using Statement : Brendan Enrick's Blog


1/3/2011 8:53:49 AM #

pingback

Pingback from brendan.enrick.com

Old Blog Favorites

brendan.enrick.com

2/7/2011 10:11:02 AM #

BobJ

You should be careful returning from within a using statement if your returned object uses the object that would be disposed!

e.g. bad code:

using ( MyFileHandle fileHandle = File.Open(myFile) )
{
    // uhoh, the returned stream needs the handle, but the handle will be disposed!!!
    return new FileStream(fileHandle);
}


BobJ United Kingdom

4/11/2011 9:02:45 AM #

trackback

Return Within a C# Using Statement

While writing some code earlier today I needed to return from within a using statement. Doing these sorts

Orcs Goblins and .NET

Comments are closed