I have a strange question about parsing enumerations from strings. Like this, my application should handle parsing multiple enumerations from a configuration file. However, I do not want to write parsing procedures for each type of enumeration (since there are many of them).
The problem I am facing is that the following code shows some weird error. Type T must be an unimaginable value type or something like that. I thought the default enums are not null?
If I restrict the type Twith where T : enum, everything else inside the body of the method (except the statement if Enum.TryParse) is underlined as an error.
Can anyone help with this weird minor issue?
Thanks Martin
public static T GetConfigEnumValue<T>(NameValueCollection config,
string configKey,
T defaultValue)
{
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;
}
if( ! Enum.TryParse<T>(configValue, out result) )
{
result = defaultValue;
}
return result;
}
( , / ), :
"T" , TEnum "System.Enum.TryParse(string, out TEnum)"