9.1.08

Method Hiding

I ran into a surprise today in C#, with a probably overly-complex system of interfaces and abstract classes. Here's some sample code:
    class Program
{
static void Main(string[] args)
{
IFoo b = new B();
b.DoWork();
((B)b).DoWork();

Console.ReadKey();
}
}

interface IFoo
{
void DoWork();
}

class A : IFoo
{
public void DoWork()
{
Console.WriteLine("A Does Work");
}
}

class B : A
{
public new void DoWork()
{
Console.WriteLine("B Does Work");
}
}

Output is:
A Does Work
B Does Work


I mistakenly expected both lines to say "B Does Work." After all, that's the point of inheritance, right? I instantiated a B, so it should map to B.DoWork(). Well, it doesn't.

The explanation is in the vtables AND the fact that I defined B.DoWork as new. I explicitly stated (without realizing) that it was not connected to IFoo's method. The vtable tried to resolve DoWork and got as far as it could..to A.

The correct way to implement this is by defining DoWork as virtual in A, then marking it override in B.

The code I present here would be useful if one wanted to define an implementation of a method that executed only when the method was casted to that specific type, rather than as a base class or interface. Not that I know of any such scenarios ..

No comments: