My EnumHelper class

Previously I've posted a few Helper Classes . This post describes my EnumHelper class. The class uses other helper classes, in particular CollectionsHelper
Related links: Overriding ToString on enum,
Mapping Text to Enum entries . Enum Helper Class Using Generics ,
My new little friend, Enum<T>,
Making C# enums more usable - the Parse() method
https://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=98356
  
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualBasic;
public class EnumHelper
{
// The code below does not have full runtime data checks (we can not require the generic parameter be an enum at compile time), but should save a little code.    //note in C++ you can say where T : enum http://weblogs.asp.net/kennykerr/archive/2005/05/16/The-Case-of-the-Missing-Generic-_2800_Parse-Method_2900_.aspx
  
//example of VB call EnumHelper.Parse(Of MenuMode))(sMode)
       public static TEnum Parse<TEnum>(string text) where TEnum : struct
        {
            string sEnum = text;
            ThrowExceptionIfNotEnum<TEnum>();
            if (!Enum.IsDefined(typeof(TEnum), text))
            { // Unfrortunately IsDefined is case sensitive //See also https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=145431
                sEnum = text.ToLower();
                if (!Enum.IsDefined(typeof(TEnum), sEnum))
                {
                    sEnum = text.ToUpper();
                    if (!Enum.IsDefined(typeof(TEnum), sEnum))
                    {
//NOTE that numeric value, passed as string is not recognized by IsDefined, but accepted by Parse. 
//  Debug.Assert(false, String.Format("The value passed (\"{0}\") is not a defined within {1}.", text, typeof(TEnum).ToString()));
                    }
                }
            }
            TEnum t = (TEnum)Enum.Parse(typeof(TEnum), text, true);
            return t;
        }
        public static List<T> ConvertToList<T>()
        {//from http://rodenbaugh.net/files/folders/18/download.aspx
            List<T> values = new List<T>();
            Array array = Enum.GetValues(typeof(T));
            foreach (T item in array)
                values.Add(item);
 
            return values;
        }
        //from http://rodenbaugh.net/files/folders/18/download.aspx
        public static string[] GetNames<T>()
        {
            return Enum.GetNames(typeof(T));
        }
        //from http://rodenbaugh.net/files/folders/18/download.aspx
        ///<typeparam name="U">usually int</typeparam>
        public static List<U> GetValues<T, U>()
        {
            List<U> values = new List<U>();
            Array array = Enum.GetValues(typeof(T));
            foreach (U item in array)
                values.Add(item);
            return values;
        }
        ///<typeparam name="ValueType">usually int</typeparam>
        public static bool AreValuesUnique<EnumType, ValueType>()
        {
            List<ValueType> valuesList = GetValues<EnumType, ValueType>();
            return CollectionsHelper.AreValuesUnique<ValueType>(valuesList);
        }
        ///<typeparam name="ValueType">usually int</typeparam>
        public static List<ValueType> FindDuplicates<EnumType, ValueType>()
        {
            List<ValueType> valuesList = GetValues<EnumType, ValueType>();
            return CollectionsHelper.FindDuplicates<ValueType>(valuesList);
        }
 
        // use Enum Description attribute to specify description
        // http://www.codeproject.com/csharp/enumwithdescription.asp
        //Also consider use ResourceManager see http://www.codeproject.com/csharp/LocalizingEnums.asp?print=true
        public static string GetDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                  (DescriptionAttribute[])fi.GetCustomAttributes(
                  typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
 
        // http://rodenbaugh.net/files/folders/18/download.aspx has generic class Enum<T> with a lot of interesting methods.
        // examples of use see http://rodenbaugh.net/archive/2006/11/01/Enum-Helper-Class-Using-Generics.aspx
        //TODO consider to use if required
        #region "Chars to Enums"
        //Not used in TSA at the moment
        public static char ValueAsChar<TEnum>(TEnum value) where TEnum : struct //ideally enum
        {
            ThrowExceptionIfNotEnum<TEnum>();
            char ch = Convert.ToChar(Convert.ToInt16(value));// Strings.Chr Convert.ToChar(AppType);
            return ch;
        }
        public static TEnum CharAsciiAsEnum<TEnum>(string schValue, TEnum enDefault) where TEnum : struct //ideally enum
        {
            ThrowExceptionIfNotEnum<TEnum>();
            TEnum enum1 = enDefault;
            if ((schValue != null) && (schValue.Length == 1))
            {
                enum1 = CharAsciiAsEnum<TEnum>(schValue[0], enDefault);
            }
            return enum1;
        }
 
 
        public static TEnum CharAsciiAsEnum<TEnum>(char chValue, TEnum enDefault) where TEnum : struct //ideally enum
        {
            ThrowExceptionIfNotEnum<TEnum>();
            TEnum enum1 = enDefault;
            short num1 = (short)Microsoft.VisualBasic.Strings.Asc(chValue);
            if (Enum.IsDefined(typeof(TEnum), num1))
            {
                enum1 = (TEnum)Enum.ToObject(typeof(TEnum), num1);
            }
            return enum1;
        }
        #endregion //"Chars to Enums"
        #region private methods
 
        private static void ThrowExceptionIfNotEnum<TEnum>()
        {
            if (!typeof(TEnum).IsEnum)
            {
                throw new ArgumentException(typeof(TEnum).ToString() + " is not an Enum");
            }
        }
        #endregion //private methods
 
}
    //The function is not required enum.ToString() does the same with "," separator
    //public static string ValueToNamesString<T>(T enValue, string sDelimeter) where T : struct
    //{
    //    if (!typeof(T).IsEnum)
    //    {
    //        throw new ArgumentException(typeof(T).ToString() + " is not an Enum");
    //    }
    //    string sRet;
    //    StringBuilder sb = new StringBuilder();
    //    foreach (T flag in Enum.GetValues(typeof(T)))
    //    {
    //       // T flag = (T)i;
    //        sRet = FlagToStringIfOn<T>(enValue, flag);
    //        if (!String.IsNullOrEmpty(sRet))
    //        {
    //            sb.Append(sRet);
    //            sb.Append(sDelimeter);
    //        }
    //    }
    //    sRet = StringHelper.TrimEnd(sb.ToString(), sDelimeter);
    //    return sRet;
    //}
    ////TODO make generic method
    //public static string FlagToStringIfOn<T>(T value, T flag) where T : struct
    //{
    //    if (!typeof(T).IsEnum)
    //    {
    //        throw new ArgumentException(typeof(T).ToString() + " is not an Enum");
    //    }
    //    string sRet = "";
    //    TODO convert to ulong to support & operator
    //    bool bOn = ((value & flag) != 0);
    //    if (bOn)
    //    {
    //        sRet = Enum.GetName(typeof(T), flag);
    //    }
    //    //TODO see https://secure.codeproject.com/csharp/masksandflags.asp
    //    return sRet;
    //}
 
posted @ Friday, April 20, 2007 12:36 PM
Print

Comments on this entry:

# re: My EnumHelper class

Left by web development company at 8/20/2009 12:52 PM
Gravatar
Excelent class , the code is clean, and it is so readable, I love the way you think and put all these to gather

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456