I am wondering if someone can please explain this to me:
class Program
{
static void Main()
{
AnotherDerivedClass d = new AnotherDerivedClass();
Console.WriteLine(d.PrintMessage());
IMsg m = d as IMsg;
//Why this prints BaseClass.
//How does it know that IMsg is implemented in the BaseClass.
Console.WriteLine(m.PrintMessage());
IMsg n = d as DerivedClass;
//Why this prints BaseClass and not DerivedClass
Console.WriteLine(n.PrintMessage());
Console.Read();
}
}
public interface IMsg
{
string PrintMessage();
}
public class BaseClass : IMsg
{
public string PrintMessage()
{
return "BaseClass";
}
}
public class DerivedClass : BaseClass
{
public new string PrintMessage()
{
return "DerivedClass";
}
}
public class AnotherDerivedClass : DerivedClass
{
public new string PrintMessage()
{
return "AnotherDerivedClass";
}
}
You have replaced the implementation in your derived classes, not overridden them. If you use the
BaseClass, the original implementation will be used.You need to make the method in the base virtual:
and override in the derived class:
to get the behaviour you specified.