Is any simple way to create method and set its body dynamically in C#?
- by greatromul
I hold body of method in string. I want to create method dynamically. But I don't know, how to set its body. I saw very tedious way using CodeDom. And I saw using Emit with OpCodes. Is any way to use ready code from string variable?
string method_body = "return \"Hello, world!\";"; //there is method body
DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method",
typeof(string), new Type[] { }); //any way to create method dynamically
//any way to set body
string result = (string)dm.Invoke(...); //I need write result in variable