Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 646
Flash Avatar asked Sep 18 '10 05:09

Flash


People also ask

How do I make an anonymous object?

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 .

Can you project a query to an anonymous type?

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.

How do you define 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.

Which of the following is used to create anonymous type?

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.


1 Answers

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); 
like image 160
Gabe Avatar answered Oct 04 '22 14:10

Gabe