Search code examples
c#disposeidisposableusingusing-statement

C# anonymous objects in "using" statements reliable?


Imagine this snippet:

using System;



public class Report {
    static int Level=0;

    public static void WriteLine(string Message) {
        Console.WriteLine("{0}{1}",new String(' ',4*Level),Message);
    }

    public class Indent:IDisposable {
        public Indent()            { Report.WriteLine("{"); ++Level; }
        void IDisposable.Dispose() { --Level; Report.WriteLine("}"); }
    }
}



class Program {
    static void Main() {
        Report.WriteLine("Started");
        Report.WriteLine("Calling submethod");
        using(new Report.Indent()) {
            Report.WriteLine("Submethod started");
            using(new Report.Indent()) Report.WriteLine("Subsub, maybe?");
            Report.WriteLine("Submethod reporting everything is fine");
            Report.WriteLine("Submethod finished");
        }
        Report.WriteLine("Finished");
    }
}

Which produces result:

Started
Calling submethod
{
    Submethod started
    {
        Subsub, maybe?
    }
    Submethod reporting everything is fine
    Submethod finished
}
Finished

Inside I'm using using(new Report.Indent()) instead of sticking to the only documented version I found, i.e. using(Report.Indent r=new Report.Indent()).

In my briefer version, however, can I be sure that Dispose() will always be called on those unnamed Indent objects, every time?

P.S.

// btw, I used word "anonymous" in the title, but I'm not sure that's what new objects that aren't assigned to any named variable should be called

Solution

  • Yes, using enures that even "anonymous objects" are always disposed of.

    Internally, using stores whatever value was used when entering the block in local variable. This stored value is disposed when exiting the block.