Search code examples
c#expressionexpression-trees

how to build expression tree for multilevel property/child property


I have the following string expression defining the object traversal "e.B.num". where e defines the root entity in my string expression

 class BTest
 {      
    public int num{get:set;}
 }

 class Test
 {
     public int sample {get; set;}
     public BTest B {get; set;} 
 }

 static void TestProperty()
 {
    Test obj = new Test();
    obj.sample = 40;
    obj.B = new BTest(){ num=5}

    Expression propertyExpr = Expression.Property(Expression.Constant(obj),"num");

    Console.WriteLine(Expression.Lambda<Func<int>>(propertyExpr).Compile()());

}

On the below statement Expression.Property(Expression.Constant(obj),"num"); I am able to get the value for the first level property "sample" but not for the second level property?

Am I missing something here? I am trying to build a binary expression post this based on the "num" property value.


Solution

  • You have to create nested property expression as you're looking for nested property.

    Expression bExpression = Expression.Property(Expression.Constant(obj), "B");
    Expression numExpression = Expression.Property(bExpression, "num");
    
    Console.WriteLine(Expression.Lambda<Func<int>>(numExpression).Compile()());//Prints 5