473,867 Members | 1,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to "cast" base class to specialized class

SA
Hi all:

I have an object of a base class that needs to be cast to an object of a
specialized class.

What is the best way to do this? (I thought about creating a constructor in
the specialized class that takes an argument of the type of the base class
and then copy property values over, but that seems like a hassle)

--
Sven.
Nov 21 '05 #1
6 11329
"SA" <in*********@fr eemail.nl> schrieb:
I have an object of a base class that needs to be cast to an object of a
specialized class.


We had a discussion about a similar topic going on in this group some weeks
ago:

<URL:http://groups.google.d e/groups?selm=%23 briLUiNFHA.2136 %40TK2MSFTNGP14 .phx.gbl>

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #2
On 2005-04-21, SA <in*********@fr eemail.nl> wrote:
Hi all:

I have an object of a base class that needs to be cast to an object of a
specialized class.

What is the best way to do this? (I thought about creating a constructor in
the specialized class that takes an argument of the type of the base class
and then copy property values over, but that seems like a hassle)


The first step would be to get the nomenclature right. The above
wouldn't cast the object, it would create a new object. If that's what
you want, a constructor or some kind of factory pattern is a reasonable
way to go, a Herfried's post contains a link to lots of info about this.

If casting is really what you want, VB.Net has a cast operator:

DirectCast(MyBa seObject, MySubClass)


Nov 21 '05 #3
SA
David:

DirectCast (or CType) doesn't work... That only works from subclass to base
class, but not the other way around.

--
Sven.

"David" <df*****@woofix .local.dom> wrote in message
news:slrnd6k7pg .7op.df*****@wo ofix.local.dom. ..
On 2005-04-21, SA <in*********@fr eemail.nl> wrote:
Hi all:

I have an object of a base class that needs to be cast to an object of a
specialized class.

What is the best way to do this? (I thought about creating a constructor in the specialized class that takes an argument of the type of the base class and then copy property values over, but that seems like a hassle)


The first step would be to get the nomenclature right. The above
wouldn't cast the object, it would create a new object. If that's what
you want, a constructor or some kind of factory pattern is a reasonable
way to go, a Herfried's post contains a link to lots of info about this.

If casting is really what you want, VB.Net has a cast operator:

DirectCast(MyBa seObject, MySubClass)

Nov 21 '05 #4
SA
Herfried:

Thanks. Role pattern is not what I am after, so the constructor idea will
have to do then.

--
Sven.

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:#X******** ******@tk2msftn gp13.phx.gbl...
"SA" <in*********@fr eemail.nl> schrieb:
I have an object of a base class that needs to be cast to an object of a
specialized class.
We had a discussion about a similar topic going on in this group some

weeks ago:

<URL:http://groups.google.de/groups?selm=...TK2MSFTNGP14.p
hx.gbl>
--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #5
On 2005-04-23, SA <in*********@fr eemail.nl> wrote:
David:

DirectCast (or CType) doesn't work... That only works from subclass to base
class, but not the other way around.


No, that's not true, which is why I said you should understand the
nomenclature before trying to understand the options.

Like I said, if what you really want is a new object, then forget any
kind of analogy to "casting" and the problem gets a lot easier.

Nov 21 '05 #6
SA
David:

Not sure how the nomenclature could get confusing... I don't want a new
object, but I end up creating one because casting an object from the base
class to a sub class is not supported.

Public Class A
End Class

Public Class B
Inherits A
End Class

Dim objA As New A
Dim objB As New B

You can write

objA = objB
objA = DirectCast(objB , A)
objA = CType(objB, A)

but not

B = A
objB = DirectCast(objA , B)
objB = CType(objA, B)

Note that no compiler warnings occur, but there are runtime exceptions
thrown (InvalidCastExc eption). So, yes, it *is* true that you can't cast an
object from a base class to an object of a subclass of that base class.

In the end, that makes sense, because you could get around any restrictions
on required property values that have been imposed on objects of the
subclass type of course... Still, it would be nice to be able to just cast.

--
Sven.

"David" <df*****@woofix .local.dom> wrote in message
news:slrnd6kp5l .8c7.df*****@wo ofix.local.dom. ..
On 2005-04-23, SA <in*********@fr eemail.nl> wrote:
David:

DirectCast (or CType) doesn't work... That only works from subclass to base class, but not the other way around.


No, that's not true, which is why I said you should understand the
nomenclature before trying to understand the options.

Like I said, if what you really want is a new object, then forget any
kind of analogy to "casting" and the problem gets a lot easier.

Nov 21 '05 #7

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

Similar topics

3
6583
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? Here's what I'm generally trying to achieve: I'm building (trying to anyway) a serialization library. Here's my design:
0
1457
by: raca | last post by:
I am trying to create a generic SOA ServiceInvoker that will accept an XML string that will be used to deserialize an object generated by XSDObjectGen. The hierarchy goes like this: Requests...Request (1..n)... Payload (1)... PayloadCollection (1) ... Payload (0...n) I have the knowledge about the root object Responses which I can create directly. However I don't know what is the type for Request and Payload (These will be versioned...
10
2623
by: LaEisem | last post by:
On-the-job, I have "inherited" a lot of old C language software. A question or two about when "casting" of null pointer constants is needed has occurred during behind-the-scenes cleanup of some of that software. That subject seems not to be addressed, at least not directly, in the C FAQ where FAQ 5.2 seems most relevant. References: * C FAQ 5.2 Null pointers (Including conditions where "casting" of null pointer...
2
2818
by: Won Won | last post by:
I am writing a click event for an array of PictureBoxes: for (int i = 0; i < 10; i++) pic.Click += new EventHandler (pic_Click); private void pic_Click (object sender, System.EventArgs e) In the event handler, I want to type cast the "sender" to a PictureBox, so I can do ((PictureBox) sender).Location to change its location rather than using a loop to compare the sender with each PictureBox in the array.
0
1597
by: Peter Afonin | last post by:
Hello: When I try to access a SQL server or a network share from an ASP.Net application that I run on my computer, I run into security problems (for instance, I cannot execute DTS package using Trusted connection or get a file information using FileInfo class). This is probably because my application is running under PETER\ASPNET account, where PETER is my computer's name. I can solve this problem by using Impersonation. However, when...
4
3844
by: Mike Cooper | last post by:
There is something about inherited classes I evidently don't know... I wrote the following class: Class Class1 inherits System.Windows.Forms.DataGridTextBoxColumn End Class There is absolutely no added functionality to it.
3
2022
by: hazz | last post by:
I get an InvalidCastException "Cast from string "6<5" to type 'Boolean is not valid. for If (CInt(objBuyInfo.Budget) & " " & arrRuleList(i).operator & " " & CInt(arrRuleList(i).LeadMemberValue)) Then where arrRuleList(i).operator = ">"
2
5011
by: Matthias Langbein | last post by:
Hi all, i want to save the position of my Addin-Toolbar to the registry. It's easy to store the position as a string with MsoBarPosition.toString(). But when I read the key, I get it as a string and I want to assign the value to the MsoBarPosition. Is there a better way than iterating over all possibilities in a CASE call? Thx, Langi
17
2525
by: arindam.mukerjee | last post by:
I was running code like: #include <stdio.h> int main() { printf("%f\n", 9/5); return 0; }
0
9925
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
9769
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
10809
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
10395
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...
0
9549
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
7948
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
7104
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();...
1
4593
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
2
4192
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.