Common enum parser in C #?

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) // 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;
}

( , / ), :

"T" , TEnum "System.Enum.TryParse(string, out TEnum)"

+3
4
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;
    }

    try
    {
        result = (T)Enum.Parse(typeof(T), configValue, true);
    }
    catch
    {
        result = defaultValue;
    }

    return result;
}
+1

Ah ok, , , Enum.TryParse.

:

public static T GetConfigEnumValue<T>(NameValueCollection config, 
                                      string configKey, 
                                      T defaultValue) // where T : ValueType

, Enum.TryParse.

where T : struct, new()

:

http://msdn.microsoft.com/en-us/library/dd783499.aspx

+1

# where T : enum, where T : struct.

, Michael.

0

you can find your answer here Create a generic method restricting T to Enum

0
source

All Articles