The following program prints
A:C(A,B)
B:C(A,B)
(as it should)
public interface I
{
string A();
}
public class C : I
{
public string A()
{
return "A";
}
public string B()
{
return "B";
}
}
public class A
{
public virtual void Print(C c)
{
Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
}
}
public class B : A
{
public new void Print(C c)
{
Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
}
public void Print(I i)
{
Console.WriteLine("B:I(" + i.A() + ")");
}
}
class Program
{
public static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Print(c);
b.Print(c);
}
}
however, if I change keyword 'new' to 'override' in class B like so:
public override void Print(C c)
all of a sudden program starts to print:
A:C(A,B)
B:I(A)
Why?
d
as a parameter to a method which expectsBase
, you would getDerived.Foo(int)
(same as writing(d as Base).Foo(10);
insideMain()
). Although it is clear how this works, I find this pretty smelly and therefore avoid method hiding in all cases. – Fpc