1

Below my code example. Why tom.Dispose() method doesn't called (I don't see message in console) despite it is in using block?

    class Program
{
    static void Main()
    {
        using (Person tom = new Person("Tom"))
        {   
            Console.WriteLine($"Name: {tom.Name}");
            try
            {
                dynamic result = new ExpandoObject();
                result.d = 1;
                Console.WriteLine(result.a.b);
            } 
            catch (Exception)
            {
                throw;
            }
        }            
    }
}

public class Person : IDisposable
{
    public string Name { get; }
    public Person(string name) => Name = name;

    public void Dispose() => Console.WriteLine($"{Name} has been disposed");
}

upd: if I modify catch block to below, tom.Dispose() is called

catch (Exception)
{
    if (tom != null)
        tom.Dispose();
    throw;
}

1 Answers1

4

The object gets disposed properly. The way the code is written, the exception is rethrown and never handled and the application terminates before it has a chance to write to the console.

This snippet does print the message:

static void Main()
{
    try
    {
        using (Person tom = new Person("Tom"))
        {   
            Console.WriteLine($"Name: {tom.Name}");
            dynamic result = new ExpandoObject();
            result.d = 1;
            Console.WriteLine(result.a.b);
        }
    }            
    catch(Exception){}
}

This produces :

Name: Tom
Tom has been disposed
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236