Search code examples
c#linqexpression-treesanonymous-types

How to use Expression to build an Anonymous Type?


In C# 3.0 you can use Expression to create a class with the following syntax:

var exp = Expression.New(typeof(MyClass));
var lambda = LambdaExpression.Lambda(exp);
object myObj = lambda.Compile().DynamicInvoke();

But how do you use Expression to create an Anonymous class?

//anonymousType = typeof(new{ Name="abc", Num=123});
Type anonymousType = Expression.NewAnonymousType???  <--How to do ?
var exp = Expression.New(anonymousType);
var lambda = LambdaExpression.Lambda(exp);
object myObj = lambda.Compile().DynamicInvoke();

Solution

  • You're close, but you have to be aware that anonymous types don't have default constructors. The following code prints { Name = def, Num = 456 }:

    Type anonType = new { Name = "abc", Num = 123 }.GetType();
    var exp = Expression.New(
                anonType.GetConstructor(new[] { typeof(string), typeof(int) }),
                Expression.Constant("def"),
                Expression.Constant(456));
    var lambda = LambdaExpression.Lambda(exp);
    object myObj = lambda.Compile().DynamicInvoke();
    Console.WriteLine(myObj);
    

    If you don't have to create many instances of this type, Activator.CreateInstance will do just as well (it's faster for a few instances, but slower for many). This code prints { Name = ghi, Num = 789 }:

    Type anonType = new { Name = "abc", Num = 123 }.GetType();
    object myObj = Activator.CreateInstance(anonType, "ghi", 789);
    Console.WriteLine(myObj);