Click here to Skip to main content
15,881,873 members
Articles / Programming Languages / C# 4.0

Mastering Expression Trees With .NET Reflector

Rate me:
Please Sign up or sign in to vote.
4.60/5 (4 votes)
5 Aug 2010CPOL 14.9K   5  
Following my last post, I received lots of enquiries about how to master the creation of expression trees.

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

The answer is .NET Reflector.

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

C#
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:

C#
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 tidying up the code a bit, I came up with this:

C#
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?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
-- There are no messages in this forum --