Pouya BCD
Pouya BCD

Reputation: 1031

Converting Types in runtime using reflection?

Please take a look at the following code:

        var val1 = ExtractValue(firstParam);
        var val2 = ExtractValue(secondParam);

        var type1 = val1.GetType();
        var type2 = val2.GetType();

        TypeConverter converter1 = TypeDescriptor.GetConverter(type1);
        TypeConverter converter2 = TypeDescriptor.GetConverter(type2);

        if (converter1 != null && converter1.CanConvertFrom(type2))
        {
            var temp = converter1.ConvertFrom(val2);
            return val1.Equals(temp);
        }
        return false;

it is a mystery for me that this code does not return true when I try it with a "int" and an Enum object. I even tried "val1.Equals((int)(val2))" in Immediate Window and the result was true but still the converter1.CanConvertFrom(type2) is false.

Could you please help me about it? Is there something that I am missing?

Thanks

Upvotes: 2

Views: 4017

Answers (2)

Simon Mourier
Simon Mourier

Reputation: 138915

Generalized type conversion is quite poor and inconsistent (in my opinion) in .NET. However for the Enum / int case, you can use the IConvertible interface, or the Convert associated utility class:

int converted = (int)Convert.ChangeType(MyEnum.MyValue, typeof(int));

or

object converted = Convert.ChangeType(myValue, myExpectedType);

As a site note, this 100% free library here: CodeFluentRuntimeClient has a class named ConvertUtilities that has a bunch of ChangeType method overloads (including a generic one) that are very versatile and useful for type conversion.

Upvotes: 6

jason
jason

Reputation: 241641

Note the remarks in the documentation:

As implemented in this class, this method always returns false. It never returns true.

The only time you'll get back a different answer is if you have a derivative of TypeConverter. But it's important to note that a lot of the derivatives of TypeConverter in the Framework (say BaseNumberConverter do NOT override CanConvertFrom.

Upvotes: 3

Related Questions