Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override overlapped method

Tags:

c#

.net

cil

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

like image 572
Alex Zhukovskiy Avatar asked Apr 27 '15 08:04

Alex Zhukovskiy


2 Answers

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
    }
}
like image 79
Brian Reichle Avatar answered Nov 07 '22 23:11

Brian Reichle


I haven't tried it out, but you could easily -

interface IA
{
  string Print();
}

interface IB
{
  string Print();
}


public abstract class A : IA
{
    IA.Print() { return "A"; }
}

public class B : IB, A
{
    IB.Print() { return "B"; }
}
like image 45
Robin Maben Avatar answered Nov 08 '22 01:11

Robin Maben