473,738 Members | 10,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

casting from base class to derive class

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?

Nov 17 '05 #1
2 1720
Locia <ro********@yah oo.it> 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 - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2

"Locia" <ro********@yah oo.it> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
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.
Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2336
by: Andy Lomax | last post by:
I'm using a library where the supplier has provided base class 'foo', and a reference counting class which wraps 'foo': ------------------- library code ----------------------- template<class T> refcount { ... // reference counting wrapper; like shared_ptr }; class foo {
2
1988
by: hswerdfe | last post by:
I have several Classes that derive from a common Base Class Each of these Classes Has a Differnt Version of a Function with the Same Short name, but different Long Name. See Bellow: // Base Class class CBase { void DoStuff(CBase* other);
3
1680
by: Kurt | last post by:
i just can't figure out why something im doing is not working correctly.... public interface IInterface { int someProperty { get; set; }
0
1310
by: Kurt Lange | last post by:
no... the array is created dynamically. and no... that defeats the purpose of what im trying todo.. encapsulate all initializing of variables in base class... derive from it... by deriving from base class, and casting, derived classes would already have their variables initialiezed(cause they have already been initialized in the base class) ....
8
2133
by: Michael | last post by:
Hi, I think my problem deals with class casting and inheritance. I want to deal with various Audio Formats, reading into memory for modification, working with it (done by different classes), and writing the result to disk afterwards. Therefore I have created some classes, e.g. WaveFileIO and AiffFileIO and MP3FileIO and AuFileIO for the In/Out operations.
6
1320
by: GarrettD78 | last post by:
Accidently posted this to the wrong group so I am reposting. This is probably a newbie question but I am a little confused about how to go next with my code. I think I want to use a factory pattern in this situation but I am having trouble getting access to properties at the presentation level. So my situation is I have a Vehicle base class. Public Class Vehicle Property BodyType as String End Class
6
1458
by: Spoon | last post by:
Hello everyone, I'm writing code where I can receive two kinds of packets. The first 12 octets are common to both packet types, i.e. they have the same semantics. The 1st type has 4 more octets in the header, then the payload. The 2nd type has 16 more octets in the header, then the payload. I was thinking I'd write a base class with two derived classes:
11
32447
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? class Derived (Base): def __init__ (self, base_object): # ( copy all attributes ) ...
5
2193
by: Ronald Raygun | last post by:
If I have the following class heirarchy: class A{ protected $m_type; function type(){return $this->m_type;} } class B extends A{} class C extends B{}
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.