Consider the following code:
object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();}
MethodInfo methodInfo = typeof(Program).GetMethod(\"Baz\"); // Fo
This is the first result in google about Casting to a reflected type.
So for reference, in case sb wonders what would be a general way of casting to a reflected type:
public static class ObjectExtensions
{
public static T CastTo(this object o) => (T)o;
public static dynamic CastToReflected(this object o, Type type)
{
var methodInfo = typeof(ObjectExtensions).GetMethod(nameof(CastTo), BindingFlags.Static | BindingFlags.Public);
var genericArguments = new[] { type };
var genericMethodInfo = methodInfo?.MakeGenericMethod(genericArguments);
return genericMethodInfo?.Invoke(null, new[] { o });
}
}