Wednesday, December 21, 2005

Polymorphism and Interfaces

The following code did not behave as I expected. It returns "A::f" twice, but I expected it to return first "A::f", then "B::f".

There are two ways of getting the desired behavior, either declaring A.f() virtual or explicitly stating that B implements I. The latter is not desirable since I don't think B should need to know that A implements I, and the former I don't think is intuitive.

Any thoughts?

public interface I
{
void f();
}
public class A : I
{
public void f() { Console.WriteLine("A::f") ;}
}
public class B : A
{
public void f() { Console.WriteLine("B::f"); }
}
public class C
{
static void Main()
{
I i1 = new A();
I i2 = new B();

i1.f();
i2.f();
}
}

1 comment:

Anonymous said...

I'm afraid this is just how the rules of polymorphism are defined in the C# language.

Your expectations of the behavior comes from your background as an Java programmer ;)

But the good thing is that you get an compiler warning on the B.f() method about it "hiding" the A.f(),

(See: Polymorphism, Method Hiding and Overriding in C#)