Generic Enum Parser.

The situation was something like, I have a CheckBoxList and it contains 10 List item with Item Text and Item Value. So when the user will select the Items I need to pass those value to the service layer. There is a corresponding Enum which contains all the CheckBoxList's items Value as Enum member. So when I will pass the selected to value to the service layer I need to pass as List of Enums.

To get the Enums which will represent the selected items of CheckBoxList, it requires a switch statement to state compiler if CheckBoxList's SelectedItem.Value is aaaa then return Enum.aaaa for example.

As a result if my CheckBoxList has items 20 then Enum has to have 20 items and switch statement has to implement 20 case statements.

Then I realize why don't I use a Generic Enum Parser, following code is just a example of what I did for that,

The Code is below,


namespace TestHarness
{
    using System;
    class Program
    {
        static void Main(string[] args)
        {
            GenericEnumParser genericEnumParser = new GenericEnumParser();
            genericEnumParser.Test();
        }
    }
 
    public class GenericEnumParser
    {
        public enum ListEnumOne
        {
            None,
            One,
            Two,
            Three
        }
        public enum ListEnumTwo
        {
            None,
            One,
            Two,
            Three
        }
 
        public void Test()
        {
            Console.WriteLine("{0}", ParseEnum("One").ToString());
 
            Console.WriteLine("{0}", ParseEnum<ListEnumOnestring>("Two").ToString());
            Console.WriteLine("{0}", ParseEnum<ListEnumTwostring>("Two").ToString());
        }
 
        public ListEnumOne ParseEnum(string item)
        {
            switch (item)
            {
                case "One":
                    return ListEnumOne.One;
                case "Two":
                    return ListEnumOne.Two;
                case "Three":
                    return ListEnumOne.Three;
            }
            return ListEnumOne.None;
        }
 
        public T1 ParseEnum<T1, T2>(T2 item)
        {
            if (string.IsNullOrEmpty(item.ToString()))
                return default(T1);
            else
            {
                return (T1)Enum.Parse(typeof(T1), Convert.ToString(item.ToString()), false);
            }
        }
    }
}

the output of the above example is as below,

One
Two
Two
Press any key to continue . .
.


Happy to get ideas from others.

Thanks mohammad

No comments:

Post a Comment