Search code examples
c#reflectionmethodsdynamiccodedom

Is any simple way to create method and set its body dynamically in C#?


I have the body of a method stored as a string and I'm looking to create this method dynamically. However, I'm unsure how to assign its body. I've come across a rather complex method using CodeDom, and another using Emit with OpCodes. Is there a simpler way to utilize the existing code from a string variable?

string method_body = "return \"Hello, world!\";"; // there is a method body
DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method",
                 typeof(string), new Type[] { }); // some way to create method dynamically
// any way to set body?
string result = (string)dm.Invoke(...); // I need to write result in a variable

Solution

  • You need to take a look at these namespaces:

    System.Reflection;
    System.CodeDom.Compiler;
    Microsoft.CSharp;
    

    This may get you started: http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm