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
Since an anonymous type doesn't have a default empty constructor, you cannot use the Expression.New(Type)
overload ... you have to provide the ConstructorInfo
and parameters to the Expression.New
method. To do that, you have to be able to get the Type ... so you need to make a "stub" instance of the anonymous type, and use that to get the Type
, and the ConstructorInfo
, and then pass the parameters to the Expression.New
method.
Like this:
var exp = Expression.New(new { Name = "", Num = 0 }.GetType().GetConstructors()[0],
Expression.Constant("abc", typeof(string)),
Expression.Constant(123, typeof(int)));
var lambda = LambdaExpression.Lambda(exp);
object myObj = lambda.Compile().DynamicInvoke();