using System.Reflection.Emit;
public static void Main()
MyClass myClass = new MyClass
PropertyInfo property = myClass.GetType().GetProperty("MyProperty1");
Func<MyClass, string> byPropertyCallToStringFunction = GetByPropertyCallToStringFunction<MyClass>(property);
string text = byPropertyCallToStringFunction(myClass);
public static Func<T, string> GetByPropertyCallToStringFunction<T>(PropertyInfo prop)
Type declaringType = prop.DeclaringType;
MethodInfo getMethod = prop.GetMethod;
Type propertyType = prop.PropertyType;
DynamicMethod dynamicMethod = new DynamicMethod(prop.Name+"_method", typeof(string), new Type[1]
}, declaringType.Module);
MethodInfo meth = (from p in propertyType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
where p.Name == "ToString"
ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
iLGenerator.Emit(OpCodes.Ldarg_0);
iLGenerator.Emit(OpCodes.Callvirt, getMethod);
iLGenerator.Emit(OpCodes.Stloc);
iLGenerator.Emit(OpCodes.Ldloca_S, 0);
iLGenerator.Emit(OpCodes.Call, meth);
iLGenerator.Emit(OpCodes.Stloc_1);
iLGenerator.Emit(OpCodes.Br_S, "IL_0012");
iLGenerator.Emit(OpCodes.Ldloc_1);
iLGenerator.Emit(OpCodes.Ret);
return (Func<T, string>)dynamicMethod.CreateDelegate(typeof(Func<T, string>));
public int MyProperty1 { get; set; }
public static string MyProperty1ToString(MyClass o)
return o.MyProperty1.ToString();