Search code examples
c#expression-trees

How to write new List<CustomClass>() in Expression Tree?


I want to know how can we represent below c# code in the expression tree.

var list = new List<CustomClass>(); 
list.add(new CustomClass());

where CustomClass is some complex type class.

Like how an array can be initialized with Expression.NewArrayInit

Thanks


Solution

  • The code that you asked is this:

    // List<CustomClass> foo;
    var listV = Expression.Variable(typeof(List<CustomClass>), "foo");
    
    // new List<CustomClass>()
    var newL = Expression.New(typeof(List<CustomClass>));
    
    // foo = new List<CustomClass>()
    var assV = Expression.Assign(listV, newL);
    
    // new CustomClass()
    var newEl = Expression.New(typeof(CustomClass));
    
    // foo.Add(new CustomClass())
    var addEl = Expression.Call(listV, "Add", null, newEl);
    
    var be = Expression.Block(new[] { listV }, assV, addEl);
    

    Note that I'm giving you a Block Expression... You can put it inside a bigger expression (or create a lambda based on it), but it isn't directly runnable (because it isn't a lambda expression)

    An example of lambda expression:

    var be = Expression.Block(new[] { listV }, assV, addEl, listV);
    
    var lambda = Expression.Lambda<Func<List<CustomClass>>>(be);
    var func = lambda.Compile();
    
    List<CustomClass> res = func();
    

    (note that I'm changing the be variable)