tags:

views:

63

answers:

2

Hi Everyone,

I'm writing some Enum functionality, and have the following:

public static T ConvertStringToEnumValue<T>(string valueToConvert, 
    bool isCaseSensitive)
{
    if (String.IsNullOrWhiteSpace(valueToConvert))
        return (T)typeof(T).TypeInitializer.Invoke(null);

    valueToConvert = valueToConvert.Replace(" ", "");
    if (typeof(T).BaseType.FullName != "System.Enum" &&
        typeof(T).BaseType.FullName != "System.ValueType")
    {
        throw new ArgumentException("Type must be of Enum and not " +
            typeof (T).BaseType.FullName);
    }

    if (typeof(T).BaseType.FullName == "System.ValueType")
    {
        return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)),
            valueToConvert, !isCaseSensitive);
    }

    return (T)Enum.Parse(typeof(T), valueToConvert, !isCaseSensitive);
}

I now call this with the following:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");

This works as expected. However, if I run this:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>(null);

it breaks with the error that the TypeInitializer is null.

Does anyone know how to solve this?

Thanks all!

+6  A: 

try

if (String.IsNullOrWhiteSpace(valueToConvert))
              return default(T);
Preet Sangha
A: 

Suggest you go to special BBS.

qizhishou
Special BBS? There's a huge range of C# knowledge here. Where exactly are you thinking?
Rup
-1 for answering with a comment
jmservera