65.9K
CodeProject is changing. Read more.
Home

Quick And Dirty Option Lists using Enums

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 8, 2011

CPOL
viewsIcon

7115

In C#, I just call ToString to get the name. It's quicker and dirtier...namespace EnumTest{ using System; using System.Linq; enum ListOfChoices : int { Yes, No, Possibly, Never, Pass } class Program { ...

In C#, I just call ToString to get the name. It's quicker and dirtier...
namespace EnumTest
{
    using System;
    using System.Linq;

    enum ListOfChoices : int
    {
        Yes,
        No,
        Possibly,
        Never,
        Pass
    }

    class Program
    {
        static void Main(string[] args)
        {
            ListOfChoices choice1 = ListOfChoices.Never;

            // Get the name for the enum value.
            string choice1Name = choice1.ToString();

            Console.WriteLine("choice1 name = " + choice1Name);

            // Since ToString() is called by WriteLine, we could just do this:
            Console.WriteLine("choice1 name = " + choice1);

            // BUT WAIT -- THERE'S MORE!
            // Get all names:
            string[] allChoiceNames = Enum.GetNames(typeof(ListOfChoices));

            // print all names
            Console.WriteLine();
            Console.WriteLine(string.Join(Environment.NewLine, allChoiceNames));

            // Get all values:
            int[] allValues = Enum.GetValues(typeof(ListOfChoices)).Cast().ToArray();

            // print all values:
            Console.WriteLine();

            for (int ndx = 0; ndx < allValues.Length; ndx++)
            {
                Console.WriteLine(allValues[ndx]);
            }

            Console.ReadKey(true);
        }
    }
}
Console Output: choice1 name = Never choice1 name = Never Yes No Possibly Never Pass 0 1 2 3 4