I have a weird question about parsing enumerations from strings. As it is, my app needs to handle parsing of few enumerations from a config file. However, I don't want to write parsing routines for each enumeration type (as there are many).
The problem I am facing is that the following code is showing some weird error - The type of T has to be a non-nullable value type or something of the sort. I thought that enums are by default non-nullable?
If I restrict the type of T
using where T : enum
, everything else inside the method body (other than the if Enum.TryParse
statement) is underlined as error.
Can anyone help with this weird minuscule issue?
Thanks, Martin
public static T GetConfigEnumValue<T>(NameValueCollection config,
string configKey,
T defaultValue) // where T : enum ?
{
if (config == null)
{
return defaultValue;
}
if (config[configKey] == null)
{
return defaultValue;
}
T result = defaultValue;
string configValue = config[configKey].Trim();
if (string.IsNullOrEmpty(configValue))
{
return defaultValue;
}
//Gives me an Error - T has to be a non nullable value type?
if( ! Enum.TryParse<T>(configValue, out result) )
{
result = defaultValue;
}
//Gives me the same error:
//if( ! Enum.TryParse<typeof(T)>(configValue, out result) ) ...
return result;
}
A user requested to post the text of the error (it is at code time, not compile/runtime), so here it goes:
The type 'T' must be a non-nullable value type in order to use it as parameter TEnum in the generic type or method 'System.Enum.TryParse(string, out TEnum)'