471,353 Members | 1,760 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Read variable from file and re-create with correct type

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?
Jan 31 '06 #1
3 1440

"Mark Ingram" <no****@nowhere.com> wrote in message
news:Oi**************@TK2MSFTNGP10.phx.gbl...
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.
Jan 31 '06 #2
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

Jan 31 '06 #3
Andy wrote:
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!
Feb 1 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Daniel Loose | last post: by
3 posts views Thread by jy836 | last post: by
6 posts views Thread by Per Juul Larsen | last post: by
reply views Thread by XIAOLAOHU | last post: by

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.