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");
    }
}

You May Also Like

About the Author: rnowik

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.