using System.Runtime.CompilerServices;
public static class ObjectExtensions
public static T CastTo<T>(this object o) => (T)o;
public static dynamic CastToType(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 });
public class MyDerivedObject : Object
public static void PrintMyType<T>(T theObject)
Console.WriteLine($"The type is now {typeof(T).Name}");
public static void Main()
var derivedObject = new MyDerivedObject();
PrintMyType(derivedObject);
Object tmp = derivedObject;
PrintMyType(tmp.CastToType(tmp.GetType()));