Friday 24 May 2013

Convert values to Enum types using Generic Methods.

Alright, so I am back again on System.Enum

I faced this problem when converting a generic type T from short to Enum with base int.

For Example:


 enum TestEnum
    {
        TestMemberA = 1,

        TestMemberB = 3
    }


The following conversion just works:


           short theValue = 1;
           TestEnum directConverted = (TestEnum)theValue;

But, when using the following it fails at "return (T)input;


 static void Main(string[] args)
        {
            short theValue = 1;
            TestEnum returnedEnum = GetValueWithError<TestEnum>(theValue);
       
        }

        public static T GetValueWithError<T>(object input)
        {
            if (input == null || Convert.IsDBNull(input))
                return default(T);
           
            return (T)input;
        }



So, to fix this issue I used the following code:



    static void Main(string[] args)
        {
            short theValue = 1;
            string stringValue = GetValue<string>(theValue);
            int intValue = GetValue<int>(theValue);
            TestEnum returnedEnum = GetValue<TestEnum>(theValue);
         
        }
        public static T GetValue<T>(object input)
        {
            if (input == null || Convert.IsDBNull(input))
                return default(T);

            Type type = typeof(T);
            if (type.IsEnum)
            {

                Type underlyingType = type.GetEnumUnderlyingType();
                if (underlyingType == input.GetType())
                    return (T)input;

                return (T)Convert.ChangeType(input, underlyingType);
            }
            return (T)Convert.ChangeType(input, type);
        }


I hope this is good enough for a programmer to understand. Sorry for the bad formatting again!.

Regards
Kajal