Alex Rivera | Logout

C# - Explicit Interfaces with inheritance?

Asked 2009-12-06T20:33:57.800
10

Output:
B->Hello! from Explicit.

Shouldn't it be:?
A->Hello! from Explicit.

Why doesn't explicit cast (IHello)a call IHello.Hello() from class A?

interface IHello
{
    void Hello();
}

class A : IHello
{

    public virtual void Hello()
    {
        Console.WriteLine("A->Hello!");
    }

    void IHello.Hello()
    {
        Console.WriteLine("A->Hello! from Explicit.");
    }
}

class B : A, IHello
{
    public override void Hello()
    {
        Console.WriteLine("B->Hello!");
    }

    void IHello.Hello()
    {
        Console.WriteLine("B->Hello! from Explicit.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a = new B();
        ((IHello)a).Hello();
    }
}
Edit
Report

1 Answer

0

No, it shouldn't.

When you are calling a virtual method, it doesn't matter what the type of the reference is. The method that is called is determined by the actual type of the object, not the type of the reference.

As you create an instance of the class B, the actual type of the object is B. The reason that it prints "This is class A." is that you have not overridden the ToString method in the class B, you have shadowed it using the new keyword. Therefore the B class has two ToString methods, one inherited from the class A and one that shadows it. If you use an A reference to call the ToString method, the inherited method is called, but if you would have used a B reference to call it, the shadowing method would be called, printing out "This is class B.".

Also if you override the ToString method in the class B instead of shadowing it, it would print out "This is class B." regardless of the type of the reference.

answered 2009-12-06T20:46:24.590

Your Answer