6
\$\begingroup\$

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))
{
  header.Property.SetValue(instanceOfTrade, value.ToInt(), null);
}
else if (header.Property.PropertyType == typeof(decimal))
{
  header.Property.SetValue(instanceOfTrade, value.ToDecimal(), null);
}
else if (header.Property.PropertyType == typeof(DateTime))
{
  header.Property.SetValue(instanceOfTrade, value.TryToDateTime(), null);
}
else
{
  header.Property.SetValue(instanceOfTrade, value.ToString(), null);
}
\$\endgroup\$
  • \$\begingroup\$ Maybe you mean "with reflection"? Is reflection mandatory approach? Could you post how does your code's consumer look like? \$\endgroup\$ – abatishchev Jul 27 '11 at 17:11
5
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.