zaagan
11/29/2017 - 5:14 AM

Enum Manipulation

Manipulate enums and convert to various types

enum Status
{
    OK = 0,
    Warning = 64,
    Error = 256
}

bool exists;
 
 exists = Enum.IsDefined(typeof(Status), 0);     // exists = true
 exists = Enum.IsDefined(typeof(Status), 1);     // exists = false
 
 
exists = Enum.IsDefined(typeof(Status), "OK");      // exists = true
exists = Enum.IsDefined(typeof(Status), "NotOK");   // exists = false
 
    public static class EnumConverter
    {
        public static string[] ToNameArray<T>()
        {
            return Enum.GetNames(typeof(T)).ToArray();
        }

        public static Array ToValueArray<T>()
        {
            return Enum.GetValues(typeof(T));
        }

        public static List<T> ToListOfValues<T>()
        {
            return Enum.GetValues(typeof(T)).Cast<T>().ToList();
        }

        public static IEnumerable<T> ToEnumerable<T>()
        {
            return (T[])Enum.GetValues(typeof(T));
        }
        
        public static T FromInt<T>(int value)
        {
            return (T)Enum.ToObject(typeof(T), value);
        }

        public static T FromString<T>(string value)
        {
            return (T)Enum.Parse(typeof(T), value);
        }
       
        
        
    }