How does one cast the return value from CreateInstance when the type is unknown?
For example in this code:
MethodInfo mInfo = typeof(MyType).GetMethod(MethodBase.GetCurrentMethod().Name);
Object o = Activator.CreateInstance(mInfo.ReturnType);
how do I cast my o to whatever mInfo.ReturnType contains?
Casting (at least, in the way you usually mean) is a compile-time / static-typed operation. The only way that even makes sense at runtime with an unknown type is when dealing either with generics (casting it to some
T– and note that you can choose theTat runtime viaMakeGenericMethodorMakeGenericType), or with meta-programming (emitting IL to do the appropriate cast). In all other cases when the type is unknown until runtime, you are stuck with eitherobjectordynamic.