Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic string parse to any object

I am storing object values in strings e.g.,

string[] values = new string[] { "213.4", "10", "hello", "MyValue"}; 

is there any way to generically initialize the appropriate object types? e.g., something like

double foo1 = AwesomeFunction(values[0]); int foo2 = AwesomeFunction(values[1]); string foo3 = AwesomeFunction(values[2]); MyEnum foo4 = AwesomeFunction(values[3]); 

where AwesomeFunction is the function I need. The ultimate use is to intialize properties e.g.,

MyObject obj = new MyObject(); PropertyInfo info = typeof(MyObject).GetProperty("SomeProperty"); info.SetValue(obj, AwesomeFunction("20.53"), null); 

The reason I need such functionality is I am storing said values in a database, and wish to read them out via a query and then initialize the corresponding properties of an object. Is this going to be possible? The entire object is not being stored in the database, just a few fields which I'd like to read & set dynamically. I know I can do it statically, however that will get tedious, hard to maintain, and prone to mistakes with numerous different fields/properties are being read.

EDIT: Bonus points if AwesomeFunction can work with custom classes which specify a constructor that takes in a string!

EDIT2: The destination type can be know via the PropertyType, in the specific case where I want to use this type of functionality. I think Enums Would be easy to parse with this e.g.,

Type destinationType = info.PropertyType; Enum.Parse(destinationType, "MyValue"); 
like image 452
mike Avatar asked Oct 19 '10 06:10

mike


1 Answers

Perhaps the first thing to try is:

object value = Convert.ChangeType(text, info.PropertyType); 

However, this doesn't support extensibility via custom types; if you need that, how about:

TypeConverter tc = TypeDescriptor.GetConverter(info.PropertyType); object value = tc.ConvertFromString(null, CultureInfo.InvariantCulture, text); info.SetValue(obj, value, null); 

Or:

info.SetValue(obj, AwesomeFunction("20.53", info.PropertyType), null); 

with

public object AwesomeFunction(string text, Type type) {     TypeConverter tc = TypeDescriptor.GetConverter(type);     return tc.ConvertFromString(null, CultureInfo.InvariantCulture, text); } 
like image 113
Marc Gravell Avatar answered Oct 02 '22 12:10

Marc Gravell