by Paulo Morgado via Paulo Morgado : C# on 8/6/2010 12:40:39 AM
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?
Original Post: Mastering Expression Trees With .NET Reflector
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.