views:

202

answers:

4

I need to convert from string that contains data to object of some type that is passed using reflection. I have an not serializable object that contains properties of any type and I want to load data to that object, for example that object has a property Color BgColor when I am trying to set "Red" value to that property I get that conversion is not possible from string to Color, I need a general code. Thanks a lot

A: 

Try Convert.ChangeType for general conversions.

But in your case I think the Color.FromName method would be best:

Creates a Color structure from the specified name of a predefined color.

Andrew Hare
No unfortunately I know about it, and it doesn't help, Can it convert 120 to System.Web.UI.WebControls.Unit for example? in xml I have a string and the width property type is Unit
ArsenMkrt
Is there a general method? Or I should use switch case or try to find parse method by reflection?
ArsenMkrt
A: 

If all you need to do is convert a string to it's value in an enum, you can use code similar to the following:

public static T ToEnum<T>(this string original)
{
    Array values = Enum.GetValues(typeof(T));

    foreach (T value in values)
    {
        if (value.ToString().ToUpperInvariant() == original.ToUpperInvariant())
            return value;
    }

    throw new NotFoundException();
}

If you need to convert other types, then perhaps specifying types and the formats of the string might help people direct you better.

Matthew Scharley
the property type is not an enum always, I am loading ASP.NET controls from xml and want to set all control properties from xml values, but ASP.NET somehow converts 129 px string to UNit type, in my case I get an error
ArsenMkrt
+3  A: 

Consider Generalized Type Conversion

Dzmitry Huba
Thanks a lot, It works
ArsenMkrt
A: 

use Convert class

Davit Siradeghyan