Read variable from file and re-create with correct type

M

Mark Ingram

Hi, if in a file i have the following:

<variable type="String">Hello World</variable>
<variable type="Int32">29</variable>

How can i create these variables in my application? (Ignore the reading
of the text in, that part is easy).

I guess it would be easy enough by doing a giant "if" statement, but
thats a horrible solution.

if (type == "Int32")
var = Int32.Parse(value);
else if (type == "String")
var = value;

etc etc



Any help or tips?
 
N

Nick Hounsome

Mark Ingram said:
Hi, if in a file i have the following:

<variable type="String">Hello World</variable>
<variable type="Int32">29</variable>

How can i create these variables in my application? (Ignore the reading of
the text in, that part is easy).

I guess it would be easy enough by doing a giant "if" statement, but thats
a horrible solution.

if (type == "Int32")
var = Int32.Parse(value);
else if (type == "String")
var = value;

etc etc
Any help or tips?

1) A dictionary mapping type names to parser delegates is the cleanest
method. It can even be set up or extended from a config file with te aid of
reflection for maximum flexibility.
2) A method that will work for a limited subset of types is simply to use
reflection to look for a Parse method on the type.
 
A

Andy

I would do this..

<variable type="System.Int32">29</variable>

Notice i fully qualify the type in the Xml.

In code you could do this..

object x = Activator.CreateInstance( type );
x = value;

return x;

HTH
 
M

Mark Ingram

Andy said:
I would do this..

<variable type="System.Int32">29</variable>

Notice i fully qualify the type in the Xml.

In code you could do this..

object x = Activator.CreateInstance( type );
x = value;

return x;

HTH

Thats great, just what i needed. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top