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();
You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .
In some cases, you might want to project a query to a new type, but the query would be your only use for the new type. Rather than create the type, you can project to an anonymous type.
Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
We can create anonymous types by using “new” keyword together with the object initializer. As you can see from the below code sample, the type is store in a var and has two data items.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With