hits counter

Mastering Expression Trees With .NET Reflector

Following my last post, I received lots of enquiries about how got to master the creation of expression trees.

The answer is: .NET Reflector

On that post I needed to to generate an expression tree for this expression:

Expression<Func<object, object>> expression = o => ((object)((SomeType)o).Property1);

I just compiled that code in Visual Studio 2010, loaded the assembly in .NET Reflector, and disassembled it to C# without optimizations (View –> Options –> Disassembler –> Optimization: None).

The disassembled code looked like this:

Expression<Func<object, object>> expression;
ParameterExpression CS$0$0000;
ParameterExpression[] CS$0$0001;
expression = Expression.Lambda<Func<object, object>>(Expression.Convert(Expression.Property(Expression.Convert(CS$0$0000 = Expression.Parameter(typeof(object), "o"), typeof(SomeType)), (MethodInfo) methodof(SomeType.get_Property1)), typeof(object)), new ParameterExpression[] { CS$0$0000 });

After giving valid C# names to the variables and tidy up the code a bit, I came up with this:

ParameterExpression parameter = Expression.Parameter(typeof(object), "o");
Expression<Func<object, object>> expression =
    Expression.Lambda<Func<object, object>>(
        Expression.Convert(
            Expression.Property(
                Expression.Convert(
                    parameter,
                    typeof(SomeType)
                ),
                "Property1"
            ),
            typeof(object)
        ),
        parameter
    );

Easy! Isn’t it?

3 Comments

  • Why are we getting variables named CS$0$0000? Is there any way to disassemble it correctly i.e. without getting such variable names?

  • No, Yasir.
    These are, actually, these variables are generated by the compiler. The C# compiler generates .NET valid but C# invalid names thus avoiding collisions with any identifier the developer might use.
    You can always Find and Replace it using regular expressions. Find CS\${:z}\${:z} (check Match whole word) and replace with CS_\1_\2.

  • Hydrating Objects With Expression Trees - Part I
    After my post about dumping objects using expression trees, I’ve been asked if the same could be done for hydrating objects.

Comments have been disabled for this content.