Click here to Skip to main content
15,884,644 members
Articles / Programming Languages / Visual Basic
Alternative
Tip/Trick

Quick And Dirty Option Lists using Enums

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
12 Sep 2011CPOL 6.9K   1   1
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)


Written By
Software Developer Insight Global
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalyou call ToString of what, give an example........ Pin
DaveAuld10-Mar-11 8:15
professionalDaveAuld10-Mar-11 8:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.