Use reflection to invoke an overridden base method

After a long time, I finally find a better solution than DynamicMethod:

class CallOverride
{
    public static void Test()
    {
        var obj = new Override();
        var method = typeof(object).GetMethod("ToString");
        var ftn = method.MethodHandle.GetFunctionPointer();
        var func = (Func<string>)Activator.CreateInstance(typeof(Func<string>), obj, ftn);
        Console.WriteLine(func());
    }
}

class Override
{
    public override string ToString()
    {
        return "Nope";
    }
}

This solution use the standard constructor signature of delegate:

public Delegate(object target, IntPtr ftn)

where target is the target instance and ftn is the function pointer.
It directly invoke it with the function pointer of base method, so the delegate will point to the actual base method, not the overridden method.

Leave a Comment