473,708 Members | 2,455 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type Casting

Hi there,

Is there anyone that knows how to do the following?

I have a class A and a class B, that 100% inherits from class A (this means
that I don't have other code in class B, than the Inherit statement).

Now I want to make a Type Casting on an object of the type A, so that object
become a B type.

I have tryied it, but gets the error 'System.Invalid CastException: Specified
cast is not valid.', so want am I missing.

Please give a hint.

René


Nov 20 '05 #1
23 3514

"René Nordby" <re**@bluedot.d k> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than the Inherit statement).

Now I want to make a Type Casting on an object of the type A, so that object become a B type.

I have tryied it, but gets the error 'System.Invalid CastException: Specified cast is not valid.', so want am I missing.


You're missing the fact that it can't be done. You can cast a derived class
into its base class, but you can't cast a base class to a derived class.
Someone correct me if I'm wrong.
Nov 20 '05 #2
Hi Jeff,

Thanks for your quick answer.

When you say so, then I thnink of String and Integer datatypes, where you
can cast from String to Integer and the other way around, so how is that
done?

I know that both String and Integer is derived from Object, so I have also
tryied to let my two classes inherit from a base class, but it give me the
same result.

"Jeff Johnson [MVP: VB]" <i.***@enough.s pam> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..

"René Nordby" <re**@bluedot.d k> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I have a class A and a class B, that 100% inherits from class A (this means
that I don't have other code in class B, than the Inherit statement).

Now I want to make a Type Casting on an object of the type A, so that

object
become a B type.

I have tryied it, but gets the error 'System.Invalid CastException:

Specified
cast is not valid.', so want am I missing.


You're missing the fact that it can't be done. You can cast a derived

class into its base class, but you can't cast a base class to a derived class.
Someone correct me if I'm wrong.

Nov 20 '05 #3
Hi Jeff,
You're missing the fact that it can't be done. You can cast a derived class into its base class, but you can't cast a base class to a derived class.
Someone correct me if I'm wrong.


You can indeed cast a base class reference to a sub-class reference and the
operation would result in a 'narrowing' conversion. BUT the conversion will
succeed ONLY if the base class reference you are trying to cast was
originally obtained from an earlier widening conversion from sub-class to
base-class.
Nov 20 '05 #4
Could you please spell it out a little more?

René

"Nice Chap" <Ni******@Plasm aDyne.com> wrote in message
news:uk******** ******@TK2MSFTN GP12.phx.gbl...
Hi Jeff,
You're missing the fact that it can't be done. You can cast a derived class
into its base class, but you can't cast a base class to a derived class.
Someone correct me if I'm wrong.


You can indeed cast a base class reference to a sub-class reference and

the operation would result in a 'narrowing' conversion. BUT the conversion will succeed ONLY if the base class reference you are trying to cast was
originally obtained from an earlier widening conversion from sub-class to
base-class.

Nov 20 '05 #5
René

Have a look at this page.

http://msdn.microsoft.com/library/de...directcast.asp

Maybe it makes some things clear.

Cor
Nov 20 '05 #6
"Nice Chap" <Ni******@Plasm aDyne.com> wrote in
news:uk******** ******@TK2MSFTN GP12.phx.gbl:
You can indeed cast a base class reference to a sub-class reference
and the operation would result in a 'narrowing' conversion. BUT the
conversion will succeed ONLY if the base class reference you are
trying to cast was originally obtained from an earlier widening
conversion from sub-class to base-class.


??? Can someone re-write this in clearer terms?

Thanks.

Nov 20 '05 #7
In article <Xn************ *************** *****@140.99.99 .130>, Anon-E-Moose wrote:
"Nice Chap" <Ni******@Plasm aDyne.com> wrote in
news:uk******** ******@TK2MSFTN GP12.phx.gbl:
You can indeed cast a base class reference to a sub-class reference
and the operation would result in a 'narrowing' conversion. BUT the
conversion will succeed ONLY if the base class reference you are
trying to cast was originally obtained from an earlier widening
conversion from sub-class to base-class.


??? Can someone re-write this in clearer terms?

Thanks.


What the op was saying was that, you can only cast a base class
reference to a subclass if that base class reference points to a
subclass instance.

In other words, casting a subclass to a base class is a narrowing
conversion, in that you loose access to some methods/properties of the
subclass since you'll be accessing it through the base class variable.
Casting a baseclass reference to a subclass would be a widening
conversion, since you would be picking up methods/properties. This is
not a safe operation, unless the base class reference actually points
to a subclass instance... Boy, this is confusing isn't it :) Here is
some psuedo code that may help...

class Base
end class

class SubClass
inherits base
end class

' this works
dim b as base = new subclass
dim s as subclass = ctype(b, subclass)

' and this works
dim s as subclass = new subclass
dim b as base = ctype(s, base)

' this doesn't
dim b as base = new base
dim s as subclass = ctype(b, subclass)
--
Tom Shelton [MVP]
Nov 20 '05 #8
I believe the framework uses TypeConverters to cast between Strings &
Integer and vice versa. Google TypeConverter to get more info.

hth,

Luhar

"René Nordby" <re**@bluedot.d k> wrote in message
news:OF******** ******@tk2msftn gp13.phx.gbl...
Hi Jeff,

Thanks for your quick answer.

When you say so, then I thnink of String and Integer datatypes, where you
can cast from String to Integer and the other way around, so how is that
done?

I know that both String and Integer is derived from Object, so I have also
tryied to let my two classes inherit from a base class, but it give me the
same result.

"Jeff Johnson [MVP: VB]" <i.***@enough.s pam> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..

"René Nordby" <re**@bluedot.d k> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I have a class A and a class B, that 100% inherits from class A (this

means
that I don't have other code in class B, than the Inherit statement).

Now I want to make a Type Casting on an object of the type A, so that

object
become a B type.

I have tryied it, but gets the error 'System.Invalid CastException:

Specified
cast is not valid.', so want am I missing.


You're missing the fact that it can't be done. You can cast a derived

class
into its base class, but you can't cast a base class to a derived class.
Someone correct me if I'm wrong.


Nov 20 '05 #9
Rene, I think you should be able to do this. I think there is something
else going on. I have a project right now for example with a base class
LineItem and two classes deriving (inheriting) from it OrderItem and
ShipmentItem. I can use CTYPE() to perform any of the following
conversions:

OrderItem to LineItem
LineItem to OrderItem
ShipmentItem to LineItem
LineItem to ShipmentItem

The only thing I can not do is convert OrderItem to ShipmentItem, which
makes sense because they are not the same "thing". If you think about it,
OrderItem is a LineItem and ShipmentItem is a LineItem but OrderItem is not
a ShipmentItem.. You need to ask yourself what kind of real world objects
your Classes A and B represent and whether the conversion makes sense. Or
if you want to post you code we could look at it.

Good luck!
-Carl

"René Nordby" <re**@bluedot.d k> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
Hi there,

Is there anyone that knows how to do the following?

I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than the Inherit statement).

Now I want to make a Type Casting on an object of the type A, so that object become a B type.

I have tryied it, but gets the error 'System.Invalid CastException: Specified cast is not valid.', so want am I missing.

Please give a hint.

René

Nov 20 '05 #10

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

Similar topics

5
8264
by: Suzanne Vogel | last post by:
** Isn't the 'static_cast' operator the same as traditional type casting? ie, Aren't the following ways of getting b1, b2 the same? // 'Derived' is derived from 'Base' Derived* d = new Derived(); Base* b1 = static_cast<Base*>(d); Base* b2 = (Base*)d; // traditional type casting Such is my understanding from code samples, my own uses, and this: http://www.cplusplus.com/doc/tutorial/tut5-4.html
4
3474
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A good way to do this is by example. So I will give an example and please tell me what you think: I have a base class A with a virtual destructor, and a class B that is it inherits publicly from A and defines som extra stuff.
3
1671
by: Steve Teeples | last post by:
Can someone explain how to cast an object to a specific type during runtime? // This line of code tells me the objects type. System.Type type = System.Type.GetType("string of the type"); // This line of code compares the objects, but the compiler doesn't like my casting. return ((type)object1 <= (type)object2) ? true : false; The compiler doesn't like my casting of (type)object1 or (type)object2.
10
11794
by: Bob | last post by:
This has been bugging me for a while now. GetType isn't availble for variables decalred as interface types, I have to DirectCast(somevariable, Object). In example: Sub SomeSub(ByVal Dictionary as IDictionary) If Dictionary is Nothing Then Return Dim o as Object = DirectCast(Dictionary, Object)
10
2273
by: lovecreatesbeauty | last post by:
Why (type*)pointer isn't equal to *(type**)pointer, In the code snippet, it shows that: (int *) == (int **) , (int *) != (*(int **)) . Does type-casting change the address? or doesn't type-casting do anything? 1 int main(void)
6
2520
by: crook | last post by:
I have code below and it works properly but when I'm compiling it with "--pedantic" flag, GCC(3.4.2) shows such warning: "ISO C forbids casting nonscalar to the same type". How can I change this code to get rid of this warning? /*parameters is void* type*/ struct params p = ( struct params )*( ( struct params * )parameters );
15
7611
by: shuisheng | last post by:
Dear All, Assume I have a class named Obj. class Obj { }; And a class named Shape which is derived from Obj. class Shape: public Obj
11
32420
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 ) ...
8
3149
by: Smithers | last post by:
Are there any important differences between the following two ways to convert to a type?... where 'important differences' means something more profound than a simple syntax preference of the developer. x = someObject as MySpecificType; x = (MySpecificType) someObject; Thanks.
0
8787
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
8697
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,...
0
9158
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7921
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
6615
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
4454
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
4712
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3151
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
3
2096
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.