473,728 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting Issue Correct Question! Sorry

Hi guys who just answered me.....it really would have helped if i had
written it right.

Ok i will use better names to explain my problem.

I have this:

InterFaceClass
^
ClassA
^
^
ClassB
ClassC
So i have an interface class that ClassA inherits from. ClassB and C then
inherit from classA.

i then want to do this:

ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?
Oct 20 '06 #1
14 1910

Daniel wrote:
ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?
Because some_ClassA_ins tance is not a ClassB.

Oct 20 '06 #2
Basically you can cast up you cant cast down. I get it now.


"Brian Gideon" <br*********@ya hoo.comwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
>
Daniel wrote:
>ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?

Because some_ClassA_ins tance is not a ClassB.

Oct 20 '06 #3
Daniel wrote:
Ok i will use better names to explain my problem.

I have this:

InterFaceClass
^
ClassA
^
^
ClassB
ClassC
So i have an interface class that ClassA inherits from. ClassB and C then
inherit from classA.

i then want to do this:

ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?
If we use different names, maybe it will be clearer:

interface IAnimal //Animal Interface
class AnimalBase : IAnimal //Animal base class

class Dog : AnimalBase //A Dog is an animal
class Cat : AnimalBase //A Cat in an animal

AnimalBase obj = new AnimalBase(); //This is a generic animal,
it could be anything

Dog myDog = (Dog)obj; //Try to cast generic animal to Dog
//This is not valid because an
animal may not be a dog

AnimalBase obj = new Dog(); //This is valid because a Dog *is* an
Animal
//However you can only
access the properties of a
//Generic animal

Dog myDog = (Dog)obj; //This is now valid because obj is
actually a Dog
Cat myCat = (Cat)obj; //This is *invalid* because obj is
*not* a Cat.

Hope this helps a little.

Chris

Oct 20 '06 #4
Well in regrds to this.

The situation i have is that I want the class A object to have certain
methods overridden and its behaviour changed, class B and C.

So if i want ClasC implementation i cast it....(i now know i cant). So how
using that setup do i get that requirement?

"Daniel" <Da*****@vestry online.comwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
Hi guys who just answered me.....it really would have helped if i had
written it right.

Ok i will use better names to explain my problem.

I have this:

InterFaceClass
^
ClassA
^ ^
ClassB ClassC
So i have an interface class that ClassA inherits from. ClassB and C then
inherit from classA.

i then want to do this:

ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?

Oct 20 '06 #5
Can i ask then....

How would you then tell a generic animal object later that it is now a dog
object? You can't cast it so what do you do? Can this be done? i have a
sense a factory pattern solves my problem but i am not sure.

"Chris Dunaway" <du******@gmail .comwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
Daniel wrote:
>Ok i will use better names to explain my problem.

I have this:

InterFaceClass
^
ClassA
^
^
ClassB
ClassC
So i have an interface class that ClassA inherits from. ClassB and C then
inherit from classA.

i then want to do this:

ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?

If we use different names, maybe it will be clearer:

interface IAnimal //Animal Interface
class AnimalBase : IAnimal //Animal base class

class Dog : AnimalBase //A Dog is an animal
class Cat : AnimalBase //A Cat in an animal

AnimalBase obj = new AnimalBase(); //This is a generic animal,
it could be anything

Dog myDog = (Dog)obj; //Try to cast generic animal to Dog
//This is not valid because an
animal may not be a dog

AnimalBase obj = new Dog(); //This is valid because a Dog *is* an
Animal
//However you can only
access the properties of a
//Generic animal

Dog myDog = (Dog)obj; //This is now valid because obj is
actually a Dog
Cat myCat = (Cat)obj; //This is *invalid* because obj is
*not* a Cat.

Hope this helps a little.

Chris

Oct 20 '06 #6
"Daniel" <Da*****@vestry online.comwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
Can i ask then....

How would you then tell a generic animal object later that it is now a dog
object?
If you initially created the object as a generic animal, you can't. The
type of an object cannot change during its lifetime. If it wasn't a Dog to
start with, it will never be a Dog.

If you like, you can create a Dog class that takes as a parameter to the
constructor an Animal instance, and then copies the information from that
Animal to a *new* Dog instance. That would allow you a way to create a
*new* Dog that inherits the generic characteristics of the Animal instance
you have (or the Animal-specific characteristics of any other Animal-derived
class, for that matter). But you cannot change a generic Animal instance
that isn't already a Dog into a Dog.

Pete
Oct 20 '06 #7
Daniel <Da*****@vestry online.comwrote :
Basically you can cast up you cant cast down. I get it now.
You can cast down when the type of the actual object is compatible with
the type you're casting to, but you can't pretend that an object is of
a different type. So this is okay:

object o = "hello";
string x = (string) o;

but this isn't:

object o = new object();
string x = (string) o;

--
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
Oct 20 '06 #8
Ok i understand now.

What i dont get is this.

GenericAnimal g = (GenericAnimal) Dog;

yet if you look at g's type it remains Dog?? Why has it not become a generic
type?
"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote in message
news:12******** *****@corp.supe rnews.com...
"Daniel" <Da*****@vestry online.comwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
>Can i ask then....

How would you then tell a generic animal object later that it is now a
dog object?

If you initially created the object as a generic animal, you can't. The
type of an object cannot change during its lifetime. If it wasn't a Dog
to start with, it will never be a Dog.

If you like, you can create a Dog class that takes as a parameter to the
constructor an Animal instance, and then copies the information from that
Animal to a *new* Dog instance. That would allow you a way to create a
*new* Dog that inherits the generic characteristics of the Animal instance
you have (or the Animal-specific characteristics of any other
Animal-derived class, for that matter). But you cannot change a generic
Animal instance that isn't already a Dog into a Dog.

Pete

Oct 20 '06 #9
Then i am confused again.

My class that was i was casting down to inherited and did not have any new
methods, just one inherited method that was overidden by implementation? Why
couldnt i cast?

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
Daniel <Da*****@vestry online.comwrote :
>Basically you can cast up you cant cast down. I get it now.

You can cast down when the type of the actual object is compatible with
the type you're casting to, but you can't pretend that an object is of
a different type. So this is okay:

object o = "hello";
string x = (string) o;

but this isn't:

object o = new object();
string x = (string) o;

--
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

Oct 20 '06 #10

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

Similar topics

231
23174
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
35
2691
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
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
1309
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) ....
7
3677
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b; but it complains for the following lines
24
2470
by: pinkfloydhomer | last post by:
Is it well-defined to make a cast from a pointer to an int and back? Like: typedef struct { int whatever; } S; int main(void) {
3
3652
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
24
39154
by: AtariPete | last post by:
Hey All, I have a C# question for you regarding up casting (base to derived). I was wondering about the most elegant way (readable, less code) to cast from a base type to its derived type. Please consider the following two classes: class Base { private int m_valA;
1
2870
by: Jay Hamilton | last post by:
Hello, I am running into an invalid address alignment error on an HPUX box when I attempt to lookup a value in a STL map. The argument being passed in is a double, which is accessed from a structure; the map's key is also a double. The issue seemed to be occuring in the map's default comparison function so I implemented my own comparison operator, but then the error continued happening in my new fxn. Strangely, casting the double I...
19
1951
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I'm doing my c# more and more like i used to code c++, meaning i'm casting more often than creating an instance of objects. like : protected void gvOrderDetailsRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { switch (((Sale)e.Row.DataItem).SzPN) {
0
8894
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
8753
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
9188
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
9122
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6704
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
6012
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
4522
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4787
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3230
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.