473,563 Members | 2,916 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 1893

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
22997
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...
35
2654
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
1676
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
1302
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...
7
3654
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
2435
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
3637
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...
24
39132
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
2861
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...
19
1920
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
7664
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...
1
7638
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...
0
7948
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...
0
6250
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...
1
5484
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...
0
3642
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
923
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...

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.