Is any simple way to create method and set its body dynamically in C#?
Posted
by greatromul
on Stack Overflow
See other posts from Stack Overflow
or by greatromul
Published on 2010-06-07T05:13:29Z
Indexed on
2010/06/07
5:22 UTC
Read the original article
Hit count: 314
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
© Stack Overflow or respective owner