473,383 Members | 1,978 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 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 6537
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.