user2818430
user2818430

Reputation: 6029

Parse dynamic data where its type is a string

I have a a sql table with 2 columns, excluding PK, etc


 DataType                  Value
 --------------------------------------
 System.String             Demo
 System.Int32              23
 System.Decimal            184,54
 System.DateTime           2018-04-25 08:57:27.6305273

How can I parse dynamically the value from the Value column, as the type specified in the DataType column. There can also be different data types: bool, double, etc (Always standard ones. No customs data type so I don't need to fetch assemblies etc)

Of course I can have a dumb solution like:

 object value;

 if (DataType == "System.String")
 {
     value = Convert.ToString(XXXX);
 }

is there a better generic approach to parse this dynamically?

EDIT:

What do you guys think of this? Is it an overkill ?

Type oType = Type.GetType("System.String");

using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(VALUE_IN_HERE)))
{
    stream.Seek(0, SeekOriginal.Begin);
    var dcs = new DataContractSerializer(oType);
    return dcs.ReadObject(stream);
}

Upvotes: 4

Views: 155

Answers (3)

Andreas
Andreas

Reputation: 982

First: Don't get the String output, use a datareader if possible, a Linq Mapping or EntityFramework to access the colums.

Second: You could do it with a Factory ... or some sort of in the lack of a better name.

Dictionary<String,Func<String,object>> factory

add your methods that create the type and return it to the dictionary

factory["System.String"] = (s) => s;
factory["System.Int32"] (i) => Int32.Parse(i);

make it, that you have the type and the value in two variables and just execute

object val = factory[type](value);

You still dont have the type info, but you could go one step further:

Dictionary<String, Action<String>> factory;
factory["System.Int32"] = i => DoSomethingGeneric(Int32.Parse(i));
factory["System.String"] = s => DoSomethingGeneric(s);

private void DoSomethingGeneric<T>(T value)
{
  at least you have a type here and can do something with it
}

Still not very useful, but you mentioned generic(s).If you are willing to handle the values independently you could use this approach:

Dictionary<String, Action<String>> factory;
factory["System.Int32"] = i => DoSomethingWithInt(Int32.Parse(i));
factory["System.String"] = s => DoSomethingWithStrings(s);

Upvotes: 0

Fabi
Fabi

Reputation: 309

Type foo = typeof(data);

will return you the parsed type, even if you inherited data with type object.

Upvotes: 0

Parrish Husband
Parrish Husband

Reputation: 3178

Storing data types seems like an anti-pattern but you could do something like:

Type t = Type.GetType(DataType);
value = Convert.ChangeType(XXXX, t);

Upvotes: 4

Related Questions