PC Review


Reply
Thread Tools Rate Thread

casting from base class to derive class

 
 
Locia
Guest
Posts: n/a
 
      17th Sep 2005
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?

 
Reply With Quote
 
 
 
 
Jon Skeet [C# MVP]
Guest
Posts: n/a
 
      17th Sep 2005
Locia <(E-Mail Removed)> wrote:
> 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?

--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
 
Reply With Quote
 
Peter van der Goes
Guest
Posts: n/a
 
      17th Sep 2005

"Locia" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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.

--
Peter [MVP Visual Developer]
Jack of all trades, master of none.


 
Reply With Quote
 
 
 
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Casting a derived class to base class user Microsoft C# .NET 2 11th Dec 2008 04:12 PM
List to contain objects that derive from a generic base class alastair g Microsoft C# .NET 2 12th Dec 2007 02:19 PM
Casting a C# base class object to a derived class type. =?Utf-8?B?Q2hyaXMgQ2Fwb24=?= Microsoft C# .NET 5 3rd Jun 2005 11:35 PM
Casting a base class to a derived class =?Utf-8?B?TWFyayBNY0RvbmFsZA==?= Microsoft C# .NET 2 10th Jan 2005 04:13 PM
Why do the commandbuilder classes not derive from an interface or a base class? Hasani Microsoft ADO .NET 1 2nd Jun 2004 09:45 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 06:36 AM.