Search code examples
c#interfacenon-virtual-interface

C# call an interface method non-virtual implementation


I am new to C# and I don't understand why compiler does not complain on this code. Here is the hierarchy of classes:

interface IAble
{
    void f();
}

class AAble : IAble
{
    public void f()
    {
        Debug.Log("---->> A - Able");
    }
}

class BAble : AAble
{
    public void f()
    {
        Debug.Log("---->> B - Able");
    }
}

execution code:

        IAble i = new BAble();
        i.f();

On execution ---->> A - Able was printed. Why? How the compiler knows what function should be called?

When the decision is made of what function to call - runtime or compile time? What if I defile a new class class CAble : IAble?


Solution

  • Because AAble is implementing the IAble interface, its AAble.f is marked as the implementation of the IAble.f method for type AAble.

    BAble.f is simply hiding the AAble.f method, it is not overriding it.

    IAble o = new BAble(); o.f(); // calls AAble.f
    AAble o = new BAble(); o.f(); // calls AAble.f
    BAble o = new BAble(); o.f(); // calls BAble.f
    IAble o = new CAble(); o.f(); // calls CAble.f
    

    The decision is made at compile-time:

    // AAble.f in IL:
    .method public final hidebysig newslot virtual 
        instance void f () cil managed 
    
    // BAble.f in IL:
    .method public hidebysig 
        instance void f () cil managed
    

    Interface implementations are marked as virtual in IL, even though it wasn't marked virtual in C#. The method is also marked as final in IL, if the method would've been virtual in C#, it would not have been marked as final.