472,364 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,364 software developers and data experts.

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(string 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.CreateInstance(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 6402
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.Serializatiion.XmlIncludeAttribute Attribute in the base class
for each derived class. The System.Xml.Serialization.Serializer 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.Serializatiion.XmlIncludeAttribute 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.Reflection and System.Reflection.Emit
namespaces. As any derived type being deserialized would be in a loaded
assembly, using the System.Reflection namespace classes, one could discover
all of the derived types in all loaded assemblies at run time. One could
also discover any System.Xml.Serializatiion.XmlIncludeAttribute Attributes
that already exist in the base class. Then, using the
System.Reflection.Emit.TypeBuilder and
System.Reflection.Emit.CustomAttributeBuilder 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.co.ukwrote in message
news:ef***********@custnews.inweb.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(string 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.CreateInstance(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.co.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.CreateInstance(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.com>
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
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...
35
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...
27
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
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...
28
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!...
1
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){} ...
12
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
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...
2
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...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

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.