21

Suppose enum:

public enum SysLogsAppTypes { None, MonitorService, MonitorTool };

and here is a function to convert from the ToString() representation back to enum:

private SysLogsAppTypes Str2SysLogsAppTypes(string str)  
{  
    try  
    {  
        SysLogsAppTypes res = (SysLogsAppTypes)Enum
                                       .Parse(typeof(SysLogsAppTypes), str);  
        if (!Enum.IsDefined(typeof(SysLogsAppTypes), res)) 
            return SysLogsAppTypes.None;  
        return res;  
    }  
    catch  
    {  
    return SysLogsAppTypes.None;  
    }  
}  

Is there a way to make this Generic ??

I tried:

private T Str2enum<T>(string str)   
{  
    try  
    {  
        T res = (T)Enum.Parse(typeof(T), str);  
        if (!Enum.IsDefined(typeof(T), res)) return T.None;  
        return res;  
    }  
    catch  
    {  
        return T.None;  
    }  
}  

but I get: 'T' is a 'type parameter', which is not valid in the given context
where there is T.None

Any help ? Thanks

1
  • 2
    Just substitute default(T) for T.None and you're good to go.
    – thecoop
    Commented Oct 7, 2010 at 0:00

4 Answers 4

19

I think the default keyword is what you need:

private T Str2enum<T>(string str) where T : struct
{   
    try   
    {   
        T res = (T)Enum.Parse(typeof(T), str);   
        if (!Enum.IsDefined(typeof(T), res)) return default(T);   
        return res;   
    }   
    catch   
    {   
        return default(T);   
    }   
}   
1
  • 8
    This is the correct answer, but it's important to note that the "default" enum is whatever value is represented by 0. This is usually the first value. However, if your enum starts at 1, you will return 0 instead of any legal value in the enum. Using this method would require a caveat for this behavior or some coding standard. For instance, I've seen some enums where a NONE value is the last value, which would not work in this method. Commented Oct 7, 2010 at 0:26
5

Not the way you are trying it, but I use the method below to do this:

 public static bool EnumTryParse<E>(string enumVal, out E resOut) 
        where E : struct
 {
      var enumValFxd = enumVal.Replace(' ', '_');
      if (Enum.IsDefined(typeof(E), enumValFxd))
      {
          resOut = (E)Enum.Parse(typeof(E), 
             enumValFxd, true);
          return true;
      }
      // ----------------------------------------
      foreach (var value in
          Enum.GetNames(typeof (E)).Where(value => 
              value.Equals(enumValFxd, 
              StringComparison.OrdinalIgnoreCase)))
      {
          resOut = (E)Enum.Parse(typeof(E), value);
          return true;
      }
      resOut = default(E);
      return false;
 }

No exceptions thrown here ...

3
  • 1
    I love this solution. I always prefer a TryParse over the assumption that values are legit. Commented Oct 7, 2010 at 0:28
  • +1 - I like the TryParse pattern, but a note: by doing the Enum.IsDefined method call before attempting to convert, this will fail to convert string representations of the underlying value of an enum. That's one benefit of the try catch and then check Enum.IsDefined algorithm. I suppose you could do an int.TryParse first and add a special case for that to the above solution.
    – jball
    Commented Oct 7, 2010 at 17:49
  • @jball, by " string representations of the underlying value ", are you talking about like, "1", "12", "one" or "two" or "TwentyThree" ?? Commented Oct 7, 2010 at 18:18
4

I like to add in a defaultValue parameter for an overload of my TryParse for cases where I want a default if it can't be parsed or is null. This is most useful for parsing string.Empty or null.

Note: this implementation will revert to defaultValue if a junk value is passed in - so you may want to tweak that by throwing an exception.

public static T TryParse<T>(string value, T defaultValue) where T: struct
    {
        if (string.IsNullOrWhiteSpace(value))
            {
                return defaultValue;
            }

            T result;
            if (Enum.TryParse<T>(value, out result))
            {
                return result;
            }
            else
            {
                return defaultValue;  // you may want to throw exception here
            }
        }
    }


    ConverterMode mode = EnumUtils<ConverterMode>.TryParse(stringValue, ConverterMode.DefaultMode);
3
  • 1
    Love this version because I get to tell it what Enum/value to return if it fails, and not necessarily a 0 or other standard I must implement across all enums.
    – RoLYroLLs
    Commented Dec 2, 2015 at 3:13
  • I'm not quite sure why I don't throw an exception where I indicated here, but I think that would be a better approach Commented Dec 2, 2015 at 3:15
  • 1
    actually what i did after the Enum.TryParse was to check if it was defined with Enum.IsDefined(). If it wasn't, I also made it the default value. And i wouldn't want to throw an exception in here because it's a Try. Don't you think?
    – RoLYroLLs
    Commented Dec 2, 2015 at 3:18
1

I know this is old, but based on a few samples, I've researched along with @Simon_Weaver's solution, this is what I have:

public static T TryParse(String value, T defaultValue) where T : struct {
    if (String.IsNullOrWhiteSpace(value)) {
        return defaultValue;
    }

    T result;
    if (!Enum.TryParse(value, out result)) {
        if (Enum.IsDefined(typeof (T), result) | result.ToString().Contains(",")) {
            // do nothing
        } else {
            result = defaultValue;
        }
    } else {
        result = defaultValue;
    }

    return result;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.