# Is there a better way to convert to a specific type with reflection?

Rather than doing what is essentially a large switch statement for every possible type, is there a better more generic way of converting to a specific type with reflection? I've looked up TypeConverter but don't understand the documentation.

if (header.Property.PropertyType == typeof(Int32))
{
}
{
}
{
}
else
{
}

• Maybe you mean "with reflection"? Is reflection mandatory approach? Could you post how does your code's consumer look like? – abatishchev Jul 27 '11 at 17:11

You could use an extension method (if this is common), or a regular generic method with a "IConvertible" constraint on the desired value then call "Convert.ChangeType" in your SetValue call.

static class ObjectExtensions
{
public static void SetPropertyValue<T>(this object obj, string propertyName, T propertyValue)
where T : IConvertible
{
PropertyInfo pi = obj.GetType().GetProperty( propertyName );

if( pi != null && pi.CanWrite )
{
pi.SetValue
(
obj,
Convert.ChangeType(propertyValue, pi.PropertyType),
null
);
}
}
}

class TestObject
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}

void Main()
{
TestObject o = new TestObject();

// Propery1 == null, Property2 == 0
o.SetPropertyValue( "Property1", 1 );
o.SetPropertyValue( "Property2", "123" );
// Propery1 == 1, Property2 == 123
}


Obviously no error handling and this is assuming you want it available on all types, so I just threw it in an "ObjectExtensions" class so it'll be visible on all types.

Just adjust the constraints to fit your exact needs, or just throw it in a regular class if you don't want to use extensions.