casting from base class to derive class

L

Locia

Can I cast from base class to derive class?

class A
{

}

class B:A
{

}

A a=new A();

B b=(B) a;

I get a cast exception.
Why?
 
J

Jon Skeet [C# MVP]

Locia said:
Can I cast from base class to derive class?

You can cast a base class type reference to a derived class type
reference, but at runtime the CLR will check that the object being
referred to as actually an instance of the derived class (or null).
class A
{

}

class B:A
{

}

A a=new A();

B b=(B) a;

I get a cast exception.
Why?

Because a *isn't* an instance of B.

Consider this code:

object x = new object();
FileStream y = (FileStream) x;

How on earth could the object actually behave like a FileStream? What
file would it be reading?
 
P

Peter van der Goes

Locia said:
Can I cast from base class to derive class?

class A
{

}

class B:A
{

}

A a=new A();

B b=(B) a;

I get a cast exception.
Why?
In simple terms, because inheritance works only from the general
(superclass) to the specific (subclass), not in the reverse direction.
Class B extends class A, thus all B objects are also A objects. However, the
reverse is not true. A objects are not objects of class B.
Giving the classes names makes it clearer. Let's call A Animal and B Mammal.
It's obvious that all mammals are animals, and just as obvious that all
animals are *not* mammals.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top