Per Erik Strandberg /cv /kurser /blog

I wondered about getting the names of enums (see more about enums here [1] and here [2]) and saw an interesting blog post about getting their names here [3].

First crappy version (using reflection)

So my first implementation was this (note the use of bad and ugly system reflection):

using System;
using System.Reflection;

namespace enumToStringTest
{
    enum Weekdays
    {
        Mon, Tue, Wed, Thu, Fri, Sat, Sun
    }

    class Program
    {
        public static void Main(string[] args)
        {
            foreach (System.Reflection.FieldInfo fi in (typeof(Weekdays)).GetFields())
                if (!fi.Name.EndsWith("__")) // avoid "value__"
                    Console.WriteLine(fi.Name);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

And the output of this little test is of course:

Mon
Tue
Wed
Thu
Fri
Sat
Sun
Press any key to continue . . .

Download the source code here: [4]

Clean and simple version (thanks Amel)

Thanks to Enum.GetNames(typeof(Weekdays)) a version a lot simpler, cleaner and better is possible:


using System;

namespace enumToStringTest
{
    enum Weekdays
    {
        Mon, Tue, Wed, Thu, Fri, Sat, Sun
    }

    class Program
    {
        public static void Main(string[] args)
        {
            foreach (string day in Enum.GetNames(typeof(Weekdays)))
                Console.WriteLine(day);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

The output is still:

Mon
Tue
Wed
Thu
Fri
Sat
Sun
Press any key to continue . . .

Download the source code here: [5]

The name of an emum item

To the get string value of a particular item, for example Weekdays.Mon this simple little line can be added:

            Console.WriteLine("Monday is {0}.", Enum.GetName(typeof(Weekdays), Weekdays.Mon));

The output is as expected:

Monday is Mon.

Download complete source code here: [6]


This page belongs in Kategori Programmering