Hyperion
Hyperion

Reputation: 21

Why does my conversion/casting fails?

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

Answers (4)

oatsoda
oatsoda

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

logicnp
logicnp

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

Ricibob
Ricibob

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

Petar Minchev
Petar Minchev

Reputation: 47373

This is called polymorphism. The instance matters(which is B) not the type reference(which is A).

Upvotes: 2

Related Questions