Search code examples
c#interfacevirtual

virtual calls on overridden interface implementations


If I have two classes that both implement an interface, but also inherit, do I need to make the function virtual? eg given:

interface IDoSomething
{
    void DoSomething();
}

class A : IDoSomething
{
    public void DoSomething()
    {
        //do A
    }
}

class B : A
{
    public new void DoSomething()
    {
        //do B
    }
}

Would the following code do A or B?

IDoSomething doer = new B();
doer.DoSomething(); //do A or do B?

I'm getting confused because I'm under the impression that all inteface calls are effectively virtual, but obviously I am using the new operator to hide the base definition.


Solution

  • Here is the explanation. Already available at stackoverflow forums.

    Quoting Jeffrey Ritcher from CLR via CSharp 3rd Edition here

    The CLR requires that interface methods be marked as virtual. If you do not explicitly mark the method as virtual in your source code, the compiler marks the method as virtual and sealed; this prevents a derived class from overriding the interface method. If you explicitly mark the method as virtual, the compiler marks the method as virtual (and leaves it unsealed); this allows a derived class to override the interface method. If an interface method is sealed, a derived class cannot override the method. However, a derived class can re-inherit the same interface and can provide its own implementation for the interface’s methods.