Reputation: 21
Code of the program - 2 classes, B inherits from A, TypeH() posts the classes letter:
class Program
{
static void Main(string[] args)
{
A z = new A();
A x = new B();
B y = (B)x;
z.TypeH();
x.TypeH();
y.TypeH();
x = (A)y;
x.TypeH();
}
}
class A
{
public virtual void TypeH()
{
Console.WriteLine("A");
}
}
class B : A
{
public override void TypeH()
{
Console.WriteLine("B");
}
}
Output: A B B B Why the last output is B and not A?
Upvotes: 2
Views: 80
Reputation: 2178
In simple terms, this occurs because the override keyword will "replace" the method on the base class A, and even if you cast to this base class it remains so.
However, if you changed class B to:
public new void TypeH()
then the new keyword will just hide the base class A implementation of TypeH. In this case, when you cast down to the base class A, you will get the base class A implementation of TypeH. Your example would then print "A".
Upvotes: 0
Reputation: 5836
When calling virtual methods, the actual instance type of the object is considered, not the compile-time type using which the method call is made.
Upvotes: 2
Reputation: 7705
Because the method TypeH is virtual.
If you removed the virtual then you get derived method on a derived ref type and base method on base ref type. With virtual there is a run timecheck - if the base ref actually points to a derived type the the derived method gets called.
Upvotes: 0
Reputation: 47373
This is called polymorphism. The instance matters(which is B
) not the type reference(which is A
).
Upvotes: 2