Powerslave
Powerslave

Reputation: 457

Type of object after as cast?

Given that code:

class B
{
  public virtual string Method()
  {
     return "base";
  }
}

class D : B
{
  public override string Method()
  {
     return "derived";
  }
}

D d = new D();
B b = d as B;
b.Method();

"derived" is the output.

But why exactly? I mean, b is a new object of type B, isnt it? Or is it the same object (in memory) as d? If so, what's the runtime type of b then, B or D?

Thanks

Upvotes: 2

Views: 112

Answers (4)

thurbarh
thurbarh

Reputation: 1

B b = d as B;

I believe this line of code only cast d to the type of class B but the value still remain as 'derived'.

Upvotes: 0

KMoussa
KMoussa

Reputation: 1578

You can do

B b = new D();
b.Method();

and you'd still get "derived". As @Bathsheba mentioned, what matters is the object type not the reference.

Imagine the typical OOP example where you have a base class Shape with derived classes Circle, Square, etc. with a virtual method Area .. if you have a method like this:

void ShowArea(Shape shape)
{
    Console.WriteLine(shape.Area());
}

The fact that the reference doesn't matter (but rather the actual object type) enables a method like the above to accept any type of Shape and still print the correct area

Upvotes: 2

rory.ap
rory.ap

Reputation: 35260

b is a new object of type B, isnt it?

No, b is an existing object of type B, which points to the same object you created just above it: d. The only difference is that you have cast the object as its parent type -- B, so b is treated as a B rather than the more-derived type D.

The reason you get the output "derived" is because the method is overridden in the derived class and that's how overriding works. Just because you declare a variable (i.e. b) as its less-derived type B doesn't mean it isn't still actually the more-derived type D. That's the nature of polymorphism.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234655

The rule is simple: b is a reference to an object of type D. You could say that the run-time type of b is D but that's not particularly helpful terminology.

Upvotes: 3

Related Questions