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?
// 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With