Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Quick And Dirty Option Lists using Enums

0.00/5 (No votes)
12 Sep 2011CPOL 7.1K  
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...
C#
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<int>().ToArray();

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

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

            Console.ReadKey(true);
        }
    }
}
</int>

Console Output:
choice1 name = Never
choice1 name = Never

Yes
No
Possibly
Never
Pass

0
1
2
3
4

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)