Search code examples
c#.netcil

Override overlapped method


Question is very short, but I didn't found a solution.

Assume we have the class hierarchy

public abstract class A
{
    public virtual string Print() { return "A"; }
}

public class B : A
{
    public virtual new string Print() { return "B"; }
}

public class C : B
{
    public override string Print() { return "C"; }
} 

Is it possible to override A.Print in C class? I tried to do it as explicit interface implementation:

string A.Print() { return "C"; }

but here I get an error:

'A' in explicit interface declaration is not an interface

I think it's not possible at all, but would appreciate receiving any additional info


Solution

  • You can't in C#, but you can in IL by using the .override keyword to override which vtable slot the method will use. (note: the method name Namespace.A.Print is not significant, including the full type name in the method name is just a useful way of avoiding collisions, in the same way as C# does for explicit interface implementations)

    .class public auto ansi beforefieldinit Namespace.C
        extends [x]Namespace.B
    {
        .method private hidebysig virtual 
            instance string Namespace.A.Print () cil managed 
        {
            .override method instance string [x]Namespace.A::Print()
            .maxstack 1
            ldstr "C"
            ret
        }
    }