Skip to content

Instantly share code, notes, and snippets.

@dcastro
Created February 19, 2014 14:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcastro/9093000 to your computer and use it in GitHub Desktop.
Save dcastro/9093000 to your computer and use it in GitHub Desktop.
Build an Expression that instantiates an Anonymous Type
public void CreateExpression()
{
Type argType = typeof (MyClass);
string propertyName = "Name";
ParameterExpression paramExpression = Expression.Parameter(argType, "item");
//Create "item.Name" and "item.GetType()" expressions
var propertyAccessExpression = Expression.Property(paramExpression, propertyName);
var getTypeExpression = Expression.Call(paramExpression, "GetType", Type.EmptyTypes);
Type anonType = CreateAnonymousType<String, Type>("SelectedProp", "TypeOfProp");
//"SelectProp = item.name"
MemberBinding assignment1 = Expression.Bind(anonType.GetField("SelectedProp"), propertyAccessExpression);
//"TypeOfProp = item.GetType()"
MemberBinding assignment2 = Expression.Bind(anonType.GetField("TypeOfProp"), getTypeExpression);
//"new AnonymousType()"
var creationExpression = Expression.New(anonType.GetConstructor(Type.EmptyTypes));
//"new AnonymousType() { SelectProp = item.name, TypeOfProp = item.GetType() }"
var initialization = Expression.MemberInit(creationExpression, assignment1, assignment2);
//"item => new AnonymousType() { SelectProp = item.name, TypeOfProp = item.GetType() }"
Expression expression = Expression.Lambda(initialization, paramExpression);
}
public static Type CreateAnonymousType<TFieldA, TFieldB>(string fieldNameA, string fieldNameB)
{
AssemblyName dynamicAssemblyName = new AssemblyName("TempAssembly");
AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("TempAssembly");
TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("AnonymousType", TypeAttributes.Public);
dynamicAnonymousType.DefineField(fieldNameA, typeof(TFieldA), FieldAttributes.Public);
dynamicAnonymousType.DefineField(fieldNameB, typeof(TFieldB), FieldAttributes.Public);
return dynamicAnonymousType.CreateType();
}
public class MyClass
{
public string Name { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment