ConvertTo on Ints to Enums

Currently, the ConvertTo method does not handle mapping of two identically named properties, where the value in the source object is an int and the value in the target is an enum. I would have expected the method to convert the int value to the correlated enum value or throw an exception if no enum with that int value exists. How can I extend the ConvertTo method to work this way (or even, better, perhaps this is worthy of a change in the ConvertTo source since it seems like universal behavior)?

class Source
    int myProperty {get;set;}

class Target
    MyEnum myProperty {get;set;}

Source instanceOfSource = new Source() {myProperty = 1;}
Target instanceOfTarget = instanceOfSource.ConvertTo<Target>();

    public enum MyEnum
        OneValue = 1,
        AnotherValue = 2,
        ThirdValue = 4
1 Like

Should now be fixed with this commit which is now available from v4.5.13 that’s now on MyGet.

Thanks for the quick turnaround! I believe your implementation works if the int value matches an enum value, but if it does not, it does not throw an exception (per the Enum.ToObject docs: “Note that the conversion succeeds even if value is outside the bounds of enumType members. To ensure that value is a valid underlying value of the enumType enumeration, pass it to the IsDefined method.”). I understand that may be by design, in which case I would ask the right way for us to have the exception thrown when the conversion fails?

As a larger question, if the general design of the ConvertTo method is just to convert when possible and not raise an issue when the conversion fails/isn’t possible, I’d suggest there would be value in a parallel method that throws an exception when the conversion of a type is not possible. I think its fair to assume that someone calling ConvertTo expects the conversion to take place on identically named properties and if the conversion can’t take place an exception should be throw to make it known that there was a pair of identically named properties that could not be converted. Otherwise the user won’t be aware there was an issue.


ConvertTo converts as much as it can without error, you’ll need to use a different library if you want Exceptions thrown.

Fair enough. How can I request implementation of ConvertTo that lets us know if there is an issue converting identically named properties?