473,772 Members | 2,424 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Change Object Type at Runtime

I'm trying to do something, not sure if it's possible or even if it
makes sense, but I figured I'd throw it out there.

I have a class OrderSummary that contains information about an order. I
then have two classes that inherit OrderSummary; K_OrderSummary and
M_OrderSummary which are specific types of orders. I will not know what
type of order it is until runtime so I want to create an object of type
OrderSummary. I only want to have to choose the type once for each
order (at runtime).

for example:

OrderSummary o;

//this will be done once, when the object is created, then the rest of
the code can just use type OrderSummary
if(type.Equals( "k"){
o = new K_OrderSummary( );
}
else{
o = new M_OrderSummary( );
}

private void DoSomethingToOr der(OrderSummar y order){
order.Something (); //this would call M_OrderSummary. Something() or
K_OrderSummary. Something() depending on what type of order it is.
}

Essentially, I want to use inheritance, but be able to declare the
object as the parent type, but use the child functions.

It would be similar to doing this:

Object o = new Form();
and then expect to be able to use o as if it were a Form object. The
declaration works, because Form inherits Object, but I of course do not
have access the the Form functions.

Make any sense?

Thanks,
Yohaas

Nov 17 '05 #1
6 8279
Well, after that long winded questions - another two minutes of
serching yielded the answer: virtual.

It's easy, just make the function virtual in the base class, then
override it in the child class.
Yohaas

Nov 17 '05 #2
Makes perfect sense. What you want is something called "polymorphi sm,"
one of the basic concepts behing object oriented programming. If you
Google on "polymorphi sm" you'll find lots of information about it, in
general.

OrderSummary o;
if(type.Equals( "k"){
o = new K_OrderSummary( );
}
else{
o = new M_OrderSummary( );
}

What you're really doing in the above code is implementing something
called a "Factory Method". I suggest going the whole distance and
making a method in OrderSummary that looks like this:

public static OrderSummary Factory(string summaryType)
{
if (summaryType == "k")
{
return new K_OrderSummary( );
}
else
{
return new M_OrderSummary( );
}
}

(and then improve it even further by making constants in OrderSummary
for "k" and "m").

Your Something() method you should implementing using an "override",
like this:

public abstract class OrderSummary
{
public abstract void Something();
}

public class K_OrderSummary : OrderSummary
{
public override void Something()
{
... do something for K order summary..
}
}

public class M_OrderSummary : OrderSummary
{
public override void Something()
{
... do something for M order summary..
}
}

then, when you have code that looks like this:

OrderSummary os = OrderSummary.Fa ctory("k");
os.Something();

it will invoke the K_OrderSummary. Something() method polymorphically .

Nov 17 '05 #3
Bruce,
Thanks for the help - looks like a good solution too. I think I am
going to stick with the virtual methods though, since making abstract
methods in OrderSummary would prevent me from having non-abstract
methods. There are many common functions that I want to keep in
OrderSummary, and only override them when necessary.

Thanks again.
Yohaas

Nov 17 '05 #4
Whether OrderSummary should be abstract or not depends upon your
design. Does it make any sense to create an OrderSummary that is
neither a K_OrderSummary nor an M_OrderSummary? That is, can you say

OrderSummary os = new OrderSummary();

all by itself and it makes sense? If the answer is yes, then it should
_not_ be abstract. If the answer is "No, every order summary must be
either a K_OrderSummary or an M_OrderSummary" then it _should_ be
abstract.

Making a class abstract does _not_ stop you from adding non-abstract
methods to it. Declaring a class abstract means only two things:

1. The class has at least one method or property that is not defined in
the class (only declared), and must be defined by any child class that
you want to be able to instantiate (in your case, all child classes).
The class may have lots of non-abstract methods, but it has to have at
least one abstract method or class.

2. You cannot create an instance of the class itself, only instances of
any child classes that implement the stuff that you said was
"abstract".

Now, one reason why you might want Something() to not be abstract in
OrderSummary is if you want to provide a default implementation of it:
if it makes sense that there is a "generic" Something() that gets done
if a child class doesn't bother defining it. In that case you want to
declare it simply "virtual" and then override it in those child classes
that need behvaiour different from the default.

Nov 17 '05 #5
yohaas wrote:
Bruce,
Thanks for the help - looks like a good solution too. I think I am
going to stick with the virtual methods though, since making abstract
methods in OrderSummary would prevent me from having non-abstract
methods. [Of course you can have non-abstract methods with abstract methods in
the abstract class, actually, it's a better approach if you don't want
the OrderSummery created by declaring it abstract. So people using your
class can only declare K_OrderSummery or M_OrderSummery, not OrderSummery).

John
There are many common functions that I want to keep in OrderSummary, and only override them when necessary.

Thanks again.
Yohaas

Nov 17 '05 #6
Bruce and John,

Thanks to both of you - I had some misconceptions about abstract
classes. I will probably go back and make OrderSummary abstract, as
order will always be K or M.

Thanks again for the help.
Yohaas

Nov 17 '05 #7

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

Similar topics

1
3229
by: Bijay Kumar | last post by:
Hi Guys, I was going through the source code of Object.cs in rotor. What I found is Equals() implemented as follows: public extern virtual bool Equals(Object obj); What I don't understand is:
0
4632
by: Bijay Kumar | last post by:
Hi Guys, I was going through the source code of Object class (Object.cs in rotor). What I found is Equals() implemented as follows: public extern virtual bool Equals(Object obj); What I don't understand is:
5
7591
by: Mark Rae | last post by:
Hi, Can anyone please tell me how to convert an object say, a System.Web.Mail.MailMessage object, to a byte array and then convert the byte array to a Base64 string? Any assistance gratefully received. Best regards,
0
4088
by: Matt S | last post by:
Hello, I'm trying to build a C# client to consume an AXIS Web Service (running SOAP over HTTP). The Web Service encodes full server-side exception traces in the Soap Fault > Detail element using complex type structures declared in the WSDL file.
3
10571
by: Andy | last post by:
If I use Visual Studio.Net 2003 to generate "web references" for clients using either sproxy.exe (for C++) client or wsdl.exe (for C#) clients, the web service endpoint gets "baked" into the generated code, making it difficult, if not impossible, to change the server that the client connects to at runtime. e.g. sproxy.exe generated code that looks like this ... static const _soapmap __CCluProvider_GetCertificate_atlsoapheader_map = {
0
5200
by: hfleong | last post by:
I am trying to change the Active Directory password using C#. However, it seems to me it does not really works. I wonder what is wrong with my code. Hope somene can help me with this and thanks in advance. Below is my code : try { string dcDNS = "mypsptestdev"; //use this if you want to supply a server name DirectoryEntry userEntry = null; string currentUserName = (((string)Context.User.Identity.Name).Split('\\')) ; DirectoryEntry...
2
2657
by: Ralph | last post by:
Hi I don't understand why it's not working: function schedule(imTop){ this.tdImagesTop = imTop; } schedule.prototype.selectEl = function() { alert(this.tdImagesTop);
6
4264
by: William | last post by:
for example, I have a global object: extern Object myobj; Can gcc get this object by using string "myobj" at runtime?? I know C++ rtti doesnt support this, but I dont know if gcc can , thanks in advance.
5
1476
by: Joseph Barillari | last post by:
Hi python-list, I've just started using new-style classes and am a bit confused as to why I can't seem to alter methods with special names (__call__, etc.) of new-style class instances. In other words, I can do this: .... pass .... 33
0
9454
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
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10103
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
8934
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...
0
6713
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.