Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic string to enum conversion

Tags:

c#

generics

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

like image 427
kofifus Avatar asked Oct 06 '10 23:10

kofifus


People also ask

Can you convert string to enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

Can generic type be enum?

Unfortunately if you want to use an enum as a generic type, the obvious way of doing it doesn't work. enum is treated as a special type and Microsoft haven't implemented this (yet). However, it is possible to use enums in generics.

Can we assign string value to enum in C#?

You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

What is enum TryParse?

C# Enum TryParse() Method The TryParse() method converts the string representation of one or more enumerated constants to an equivalent enumerated object.


2 Answers

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);   
    }   
}   
like image 64
jball Avatar answered Sep 27 '22 20:09

jball


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 ...

like image 27
Charles Bretana Avatar answered Sep 27 '22 20:09

Charles Bretana