Hi Everyone,
I'm writing some Enum functionality, and have the following:
public static T ConvertStringToEnumValue<T>(string valueToConvert, bool isCaseSensitive)
{
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 (String.IsNullOrWhiteSpace(valueToConvert))
return (T)typeof(T).TypeInitializer.Invoke(null);
valueToConvert = valueToConvert.Replace(" ", "");
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 call it like this:
EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");
I now want to add constraints to T to an Enum, such as (which I got from Stackoverflow article): where T : struct, IConvertible
but I am having problems as T needs to be able to take nullable enums. Error message says:
The type 'Enums.Animals?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
Is there a way to do this, or do I need to just rely on the runtime checking which I have inside the method?
Thanks all!