CodeCopy

September 24, 2009

Converting Nullable<int> to Nullable<Enum>

Filed under: c# — mazzoo @ 13:06
Tags: , , ,

Here is an example on how you identify a Nullable enum and convert an Nullable<int> (int? ) to Nullable<Enum> ( Enum? ).


// type = typeof(MyEnum);

if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    if (type.GetGenericArguments().Length > 0 && type.GetGenericArguments()[0].IsEnum)
    {
        int? intValue = 1;
        if (intValue.HasValue)
        {
            TypeConverter convert = TypeDescriptor.GetConverter(type);
            return convert.ConvertFrom(intValue.Value + "");
        }
        return null;
    }
}

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.