Search code examples
c#reflectionexpression-trees

Is it possible to use an expression tree to define a method body for dynamic types?


If I'm creating a dynamic type like so:

TypeBuilder dynaType = dynaModule.DefineType(typeof(T).Name + "_ORMProxy");

dynaType.AddInterfaceImplementation(typeof(IServiceTable));

// (1) Implement: (String) IServiceTable.TableName { get; }
FieldBuilder tableNameField = dynaType.DefineField("tableName", typeof(String), FieldAttributes.Private);
MethodBuilder tableNamePublicGetAccessor = dynaType.DefineMethod("get_tableName", MethodAttributes.Public);
tableNamePublicGetAccessor...

Is it possible to set the GetAccessor method to an expression tree. They're much easier to work with than straight IL.


Solution

  • Yes and no. The LambdaExpression.CompileToMethod() method will let you compile an expression tree to a MethodBuilder only if the method is static. It cannot be used to implement instance methods, which I believe is what you want in your example.