Thursday, February 08, 2007

'Using' To 'Try-Finally'

Check out the following code

using (TextWriter W = File.CreateText(@"c:\log.txt"))
{
W.WriteLine("Hello");
}


When i checked the same code in ILDasm, it seems pretty different than i expected. A Try-Finally had replaced the "using" block.

------------
.locals init ([0] class [mscorlib]System.IO.TextWriter W)
IL_0000: ldstr "c:\\log.txt"
IL_0005: call class [mscorlib]System.IO.StreamWriter [mscorlib]System.IO.File::CreateText(string)
IL_000a: stloc.0
.try
{
IL_000b: ldloc.0
IL_000c: ldstr "Hello"
IL_0011: callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) IL_0016: leave.s
IL_0022
} // end .try
finally
{
IL_0018: ldloc.0
IL_0019: brfalse.s IL_0021
IL_001b: ldloc.0
IL_001c: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0021: endfinally
} // end handler
IL_0022: ret
------------

Now, wouldnt that be equavelent of writing the code as
------------

TextWriter W = File.CreateText(@"c:\log.text");
try
{
W.WriteLine("Hello");
}
finally
{
((IDisposable)W).Dispose();
}

------------

It is , both codes are equal. CLR converts the "using" statement to a "try-finally" block.