.net-3.5

How to determine what happens behind the scene in .Net


What tool or method can I use to see what code something like an anonymous method or LINQ statement gets compiled to? Basicly seeing what happens behind the scene?


Solution

  • Reflector is an excellent way to do this.

    Go to View / Options / Optimization and choose "None" so that it won't try to work out what the C# originally was.

    For example, the Main method of this little app:

    using System;
    
    class Test    
    {
        static void Main()
        {
            string other = "hello";
            Foo (x => new { Before = other + x, After = x + other });
        }
    
        static void Foo<T>(Func<int, T> func) {}
    }
    

    is decompiled to:

    private static void Main()
    {
        <>c__DisplayClass1 class2;
        class2 = new <>c__DisplayClass1();
        class2.other = "hello";
        Foo(new Func<int, <>f__AnonymousType0<string, string>>(class2.<Main>b__0));
        return;
    }
    

    and then you look in <>c__DisplayClass1 and <>f_AnonymousType0 for more details etc.