class MyBaseClass
{
virtual public void Print()
{
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass
{
override public void Print()
{
Console.WriteLine("This is the derived class.");
}
}
class Program
{
static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
derived.Print();
mybc.Print();
}
}
OUTPUT:
This is the derived class.
This is the derived class.
I do not understand why second call prints derived class's print() method because I cast mybc object to base class. I expect it to print base class print method instead. Am I missing something here?
The variable type and the instance type are two different types. Casting does not change the instance type.
When you declare a method to be virtual/abstract, you're saying that you want the instance type to determine behavior when called.
Also note that this assignment is valid - cast syntax is not needed to change variable type from subclass to baseclass. This kind of cast can be done implicitly.
MyBaseClass mybc = derived;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With