Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Quick And Dirty Option Lists using Enums

, 12 Sep 2011
Rate this:
Please Sign up or sign in to vote.
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<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)

About the Author

ChunkyStool
Software Developer Insight Global
United States United States
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 12 Sep 2011
Article Copyright 2011 by ChunkyStool
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid