473,599 Members | 3,183 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to avoid a big switch statement to create a type/subtype

I have a method. It takes some XML as a parameter. Depending on the
content of the XML it should create a specific object and call a KNOWN
method.

So: public void PersistXml(stri ng XmlData){}

I then determine what object I should call the Persist method on using a
switch statement (not very OO).

switch (otype)
{
case "type1"
switch (osubtype)
{
case "subtype1"
//create type
foo x = new foo();
x.Persist();
break;
case "subtype2"
foo2 x = new foo2();
x.Persist()
break;
}
case "..."
foo3 x = new foo3()
x.Persist();
break;
}

I can see from here that I really just have one method (Persist) and
that all I'm really doing is creating the right object at run-time and
then calling a known method on it.

I was thinking that perhaps I could create the objects at runtime and
use an interface for the known method to then call it:

object o = Activator.Creat eInstance(type) ;
IPersist persist = o as IPersist; //IPersist is same sig as PersistXml
if (persist != null)
{
persist.Persist (XmlData);
}

But being a novice I'm not really sure if there is a better way (or if
there are even issues with implementing it this way). It seems to me
that I shouldn't be worried with what object should be created, and that
I should be able to have the correct Persist method called for me using
Polymorphic code, yet if I have to create the subtype then I surely need
to know its type? I could use virtual methods and overrides but this
doesn't help me with the object creation and if I need to know the
subtype to create it, then I dont need polymorphic behaviour since I can
just call the method on it directly since I will have a reference to the
specific object.

What's the cleanest way to implement this. Either way the switch
statement has to go! :-)
Oct 1 '06 #1
2 6573
I had a similar problem to solve, which I did by creating an
XML-serializable base class from which all of the types are derived. Note
that this is slightly different from your problem in that I do not parse an
XmlDocument instance, but de-serialize a class from an XML file that is a
serialized instance of a derived class). The base class can be used to do
the de-serialization without knowing the derived type.

The tricky part is that there must be a
System.Xml.Seri alizatiion.XmlI ncludeAttribute Attribute in the base class
for each derived class. The System.Xml.Seri alization.Seria lizer instance
used to deserialize the class instance must have information about the extra
members of the derived class in order to be able to deserialize it. Of
course, the problem is that the class may be extended with additional
derived types in the future. Due to time limitations I simply add a new
System.Xml.Seri alizatiion.XmlI ncludeAttribute Attribute to the base class
whenever I create a derived class from it. Of course, this is not the best
solution, but the best solution, which is entirely doable, is a bit
complicated to implement. I plan to do this someday, but for now, in case
you want to, I will give you an overview of how it would be done.

It would be done using the System.Reflecti on and System.Reflecti on.Emit
namespaces. As any derived type being deserialized would be in a loaded
assembly, using the System.Reflecti on namespace classes, one could discover
all of the derived types in all loaded assemblies at run time. One could
also discover any System.Xml.Seri alizatiion.XmlI ncludeAttribute Attributes
that already exist in the base class. Then, using the
System.Reflecti on.Emit.TypeBui lder and
System.Reflecti on.Emit.CustomA ttributeBuilder classes, the necessary extra
derived class Attributes could be added to the base class type at run-time.

Once the class is de-serialized, it is a simple matter to determine the
derived type of the instance that was created by the Serializer.

--
HTH,

Kevin Spencer
Microsoft MVP
Software Composer
http://unclechutney.blogspot.com

A watched clock never boils.

"Angel Of Death" <af***@23o.1f.c o.ukwrote in message
news:ef******** ***@custnews.in web.co.uk...
>I have a method. It takes some XML as a parameter. Depending on the
content of the XML it should create a specific object and call a KNOWN
method.

So: public void PersistXml(stri ng XmlData){}

I then determine what object I should call the Persist method on using a
switch statement (not very OO).

switch (otype)
{
case "type1"
switch (osubtype)
{
case "subtype1"
//create type
foo x = new foo();
x.Persist();
break;
case "subtype2"
foo2 x = new foo2();
x.Persist()
break;
}
case "..."
foo3 x = new foo3()
x.Persist();
break;
}

I can see from here that I really just have one method (Persist) and
that all I'm really doing is creating the right object at run-time and
then calling a known method on it.

I was thinking that perhaps I could create the objects at runtime and
use an interface for the known method to then call it:

object o = Activator.Creat eInstance(type) ;
IPersist persist = o as IPersist; //IPersist is same sig as PersistXml
if (persist != null)
{
persist.Persist (XmlData);
}

But being a novice I'm not really sure if there is a better way (or if
there are even issues with implementing it this way). It seems to me
that I shouldn't be worried with what object should be created, and that
I should be able to have the correct Persist method called for me using
Polymorphic code, yet if I have to create the subtype then I surely need
to know its type? I could use virtual methods and overrides but this
doesn't help me with the object creation and if I need to know the
subtype to create it, then I dont need polymorphic behaviour since I can
just call the method on it directly since I will have a reference to the
specific object.

What's the cleanest way to implement this. Either way the switch
statement has to go! :-)

Oct 1 '06 #2
Angel Of Death <af***@23o.1f.c o.ukwrote:
I have a method. It takes some XML as a parameter. Depending on the
content of the XML it should create a specific object and call a KNOWN
method.
<snip>
I was thinking that perhaps I could create the objects at runtime and
use an interface for the known method to then call it:

object o = Activator.Creat eInstance(type) ;
IPersist persist = o as IPersist; //IPersist is same sig as PersistXml
if (persist != null)
{
persist.Persist (XmlData);
}
That's exactly the way to do it.
But being a novice I'm not really sure if there is a better way (or if
there are even issues with implementing it this way). It seems to me
that I shouldn't be worried with what object should be created, and that
I should be able to have the correct Persist method called for me using
Polymorphic code, yet if I have to create the subtype then I surely need
to know its type?
Exactly. If you look at the code you've got, you're only using the type
in order to create the instance, not to call the method, which is just
right.

--
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 2 '06 #3

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

Similar topics

1
3420
by: Stephen Patten | last post by:
Hi All, While in the process of building my table (40 or so Insert statments) can I then query ("select * from @Table_variable") and use the results up to theat point for another insert into @Table_varible? If you look for stepID -15 I have commented that section out due to it not retuning the correct values. Thank you in advance
35
8325
by: Thomas Matthews | last post by:
Hi, My son is writing a program to move a character. He is using the numbers on the keypad to indicate the direction of movement: 7 8 9 4 5 6 1 2 3 Each number has a direction except for '5'. So in his switch statement, he omits a case for '5':
27
5624
by: Yuriy Solodkyy | last post by:
Hi VS 2005 beta 2 successfully compiles the following: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program {
13
4520
by: Fei Liu | last post by:
Hi Group, I've got a problem I couldn't find a good solution. I am working with scientific data files in netCDF format. One of the properties of netCDF data is that the actual type of data is only known at run time. Therefore a lot of template based trick isn't too useful. Considering datafile float x(3) 3.5, 2.5, 8.9 double y(3) 2.7, -2.3, 1.2 int z(3) 5, 2, 3
28
2928
by: Steven Bethard | last post by:
Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions! PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $
1
510
by: Angel Of Death | last post by:
I have a method. It takes some XML as a parameter. Depending on the content of the XML it should create a specific object and call a KNOWN method. So: public void PersistXml(string XmlData){} Inside this method I determine what object I should call the Persist method on using a switch statement (not very OO). switch (otype)
12
12301
by: | last post by:
Is it fine to call another method from Switch? Eg. Switch (stringVar) { case ("a"): somVar = "whatever"; Another_Method(); //call another method return;
6
1794
by: asadikhan | last post by:
Hello, I have a bit of a design issue around this application I am developing, and I just want to run it through some of the brains out here. So I have a table called ErrorCheck which contains fields ErrorID (PK) and ErrorName. There is another table called Client which contains fields ClientID (PK) and ClientName. Then there is a relationship table called ClientErrorCheck which contains foreign keys ErrorID and
2
2874
osward
by: osward | last post by:
Hello there, I am using phpnuke 8.0 to build my website, knowing little on php programing. I am assembling a module for my member which is basically cut and paste existing code section of various module that I found it useful. Here is the 1st problem I encounter: I had a function to edit a event row form the database which is fine with me, than I pass on the code to a function that save(update) the data to the database.
0
7993
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
7916
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
8404
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...
1
8053
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
6729
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
5440
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
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2418
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
0
1252
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.