C#: Does dispose run when you are returning inside a using block?

Consider the code below. I wanted to confirm that the dispose method on an idisposable object got executed when you returned within an using statement. The anwser is yes: the dispose method runs before execution is passed to the caller method.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(callTestUsing.testUsing());
    }
}
public class callTestUsing
{
    public static string testUsing()
    {
        using (MyDisposingClass myDispose = new MyDisposingClass())
        {
            return "Return from testusing";
        }
    }
}
public class MyDisposingClass : IDisposable 
{
    public void Dispose()
    {
        Console.WriteLine("Disposing");
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>