Search code examples
c#ilspydotpeek

'using' block compiler generated code not visible in dotPeek or ILSpy


I am interested to look at the compiler generated code for the using code block which generates try-finally, but I do not see both dotPeek and ILSpy showing this detail. I used ildasm.exe to look at this code block and I see that it has the try-finally block in it but cannot understand it well...so wanted to see if these 2 tools would help.

Any ideas?

UPDATED: So I recently used a struct which implemented IDisposable in my project and was worried if the using code block and struct with IDisposable would cause boxing...but I later found the following article which mentioned that the compiler optimizes for this situation and does not box when trying to call Dispose.

http://ericlippert.com/2011/03/14/to-box-or-not-to-box/

So I was curious to see what kind of code does the compiler generate for my using block.

A simple example repro: enter image description here


Solution

  • The free JustDecompile tool from Telerik is able to show the details.

    Basically (Test being a sample class implementing IDisposable), the compiled version of:

    internal class Program
    {
        private static void Main(string[] args)
        {
            using (var test = new Test())
            {
                test.Foo();
            }
    
            Console.ReadLine();
        }
    }
    

    is decompiled to:

    internal class Program
    {
        public Program()
        {
        }
    
        private static void Main(string[] args)
        {
            Test test = new Test();
            try
            {
                test.Foo();
            }
            finally
            {
                if (test != null)
                {
                    ((IDisposable)test).Dispose();
                }
            }
            Console.ReadLine();
        }
    }