By Ian Boyd


2008-09-19 20:34:50 8 Comments

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

And it gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

29 comments

@reza akhlaghi 2019-10-05 14:53:31

I tried many ways and got the result from this code:

For getting a list of int from an enum, use the following. It works!

List<int> listEnumValues = new List<int>();
YourEnumType[] myEnumMembers = (YourEnumType[])Enum.GetValues(typeof(YourEnumType));
foreach ( YourEnumType enumMember in myEnumMembers)
{
    listEnumValues.Add(enumMember.GetHashCode());
}

@reza akhlaghi 2019-12-11 09:33:21

tanx for edit @peter-mortensen

@MUT 2017-03-31 07:08:44

Add method public static IEnumerable<T> GetValues<T>() to your class, like:

public static IEnumerable<T> GetValues<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

Call and pass your enum. Now you can iterate through it using foreach:

 public static void EnumerateAllSuitsDemoMethod()
 {
     // Custom method
     var foos = GetValues<Suit>();
     foreach (var foo in foos)
     {
         // Do something
     }
 }

@Kylo Ren 2016-01-22 18:50:07

There are two ways to iterate an Enum:

1. var values =  Enum.GetValues(typeof(myenum))
2. var values =  Enum.GetNames(typeof(myenum))

The first will give you values in form on an array of **object**s, and the second will give you values in form of an array of **String**s.

Use it in a foreach loop as below:

foreach(var value in values)
{
    // Do operations here
}

@Kylo Ren 2016-04-27 09:21:05

Who is down voting....it works perfectly... and at least add a comment what they think is wrong?

@Learning-Overthinker-Confused 2016-06-20 06:19:01

downvoting without even giving the reason is really not fair

@nawfal 2017-05-17 15:38:33

Maybe 'cos this is already covered in many answers? Let's not make answers redundant.

@Kylo Ren 2017-05-18 05:39:08

@nawfal yes may be covered in other answers, though not concluded well in most of them.

@anar khalilov 2014-04-08 15:44:35

I know it is a bit messy, but if you are fan of one-liners, here is one:

((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));

@Mikael Dúi Bolinder 2019-03-01 15:02:34

Is that lisp?

@nawfal 2013-08-12 15:36:47

Three ways:

  1. Enum.GetValues(type) // Since .NET 1.1, not in Silverlight or .NET Compact Framework
  2. type.GetEnumValues() // Only on .NET 4 and above
  3. type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)) // Works everywhere

I am not sure why GetEnumValues was introduced on type instances. It isn't very readable at all for me.


Having a helper class like Enum<T> is what is most readable and memorable for me:

public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
    public static IEnumerable<T> GetValues()
    {
        return (T[])Enum.GetValues(typeof(T));
    }

    public static IEnumerable<string> GetNames()
    {
        return Enum.GetNames(typeof(T));
    }
}

Now you call:

Enum<Suit>.GetValues();

// Or
Enum.GetValues(typeof(Suit)); // Pretty consistent style

One can also use some sort of caching if performance matters, but I don't expect this to be an issue at all.

public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
    // Lazily loaded
    static T[] values;
    static string[] names;

    public static IEnumerable<T> GetValues()
    {
        return values ?? (values = (T[])Enum.GetValues(typeof(T)));
    }

    public static IEnumerable<string> GetNames()
    {
        return names ?? (names = Enum.GetNames(typeof(T)));
    }
}

@krowe2 2017-12-19 17:03:01

This is a nice summary of methods. I think you should merge your other answer into this though. The truth is that enum are special and looping through them is often (usually) just as valid as enumeration because you know that the values will never change. IOW, If you have an enum that is changing all the time then you've chosen the wrong data construct to begin with.

@Darkside 2013-06-15 08:22:46

Just by combining the top answers, I threw together a very simple extension:

public static class EnumExtensions
{
    /// <summary>
    /// Gets all items for an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum
    {
        return (T[])Enum.GetValues(typeof (T));
    }
}

It is clean, simple, and, by @Jeppe-Stig-Nielsen's comment, fast.

@Yahoo Serious 2018-07-27 14:57:05

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

@sircodesalot 2013-03-17 04:15:08

Use Cast<T>:

var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();

There you go, IEnumerable<Suit>.

@Aluan Haddad 2017-12-11 11:58:01

This also works in the from clause and the foreach header declarator.

@nawfal 2013-01-25 00:05:04

I do not hold the opinion this is better, or even good. I am just stating yet another solution.

If enum values range strictly from 0 to n - 1, a generic alternative is:

public void EnumerateEnum<T>()
{
    int length = Enum.GetValues(typeof(T)).Length;
    for (var i = 0; i < length; i++)
    {
        var @enum = (T)(object)i;
    }
}

If enum values are contiguous and you can provide the first and last element of the enum, then:

public void EnumerateEnum()
{
    for (var i = Suit.Spade; i <= Suit.Diamond; i++)
    {
        var @enum = i;
    }
}

But that's not strictly enumerating, just looping. The second method is much faster than any other approach though...

@jhilden 2012-10-25 21:20:52

Here is a working example of creating select options for a DDL:

var resman = ViewModelResources.TimeFrame.ResourceManager;

ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
      in Enum.GetValues(typeof(MapOverlayTimeFrames))
      select new SelectListItem
      {
         Value = timeFrame.ToString(),
         Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
      };

@James 2012-02-02 13:36:08

I think this is more efficient than other suggestions because GetValues() is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit is not an enum.

EnumLoop<Suit>.ForEach((suit) => {
    DoSomethingWith(suit);
});

EnumLoop has this completely generic definition:

class EnumLoop<Key> where Key : struct, IConvertible {
    static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
    static internal void ForEach(Action<Key> act) {
        for (int i = 0; i < arr.Length; i++) {
            act(arr[i]);
        }
    }
}

@svick 2012-02-06 12:09:08

Careful with using generics like this. If you try to use EnumLoop with some type that is not an enum, it will compile fine, but throw an exception at runtime.

@James 2012-02-07 12:13:14

Thank you svick. Runtime exceptions will actually occur with the other answers on this page... except this one because I have added "where Key : struct, IConvertible" so that you get a compile time error in most cases.

@Alex Blokha 2012-07-30 11:25:48

No, GetValues() is called only once in the foreach.

@Grant M 2015-01-19 04:00:32

James, I would discourage your class because clever is nice to write but in production code that many people will maintain and update, clever is extra work. If it makes a major saving or will be used a lot - so the savings is big and people will become familiar with it - it is worth it, but in most cases it slows down people trying to read and update the code and introduces a possible source bugs in the future. Less code is better :) less complexity is even better.

@Jack 2015-12-16 18:36:09

@James Could you pls give an example for binding this enum values to a DropDownList in MVC?

@Dispersia 2017-05-16 18:30:32

@GrantM Why? This code is neither complex, and it's incredibly short. On top of that, writing the class once will allow even shorter iterations of code with using is as per his example. This is extremely clean, if you can't update that code, you probably can't update any of the companies code.

@Yahoo Serious 2018-07-27 14:48:51

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where Key: Enum

@Aubrey Taylor 2010-11-17 01:29:29

You won't get Enum.GetValues() in Silverlight.

Original Blog Post by Einar Ingebrigtsen:

public class EnumHelper
{
    public static T[] GetValues<T>()
    {
        Type enumType = typeof(T);

        if (!enumType.IsEnum)
        {
            throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
        }

        List<T> values = new List<T>();

        var fields = from field in enumType.GetFields()
                     where field.IsLiteral
                     select field;

        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(enumType);
            values.Add((T)value);
        }

        return values.ToArray();
    }

    public static object[] GetValues(Type enumType)
    {
        if (!enumType.IsEnum)
        {
            throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
        }

        List<object> values = new List<object>();

        var fields = from field in enumType.GetFields()
                     where field.IsLiteral
                     select field;

        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(enumType);
            values.Add(value);
        }

        return values.ToArray();
    }
}

@nawfal 2013-11-07 09:10:08

Nice solution, but some refactoring will be better! :)

@Ananda 2015-12-30 06:41:18

I am using .NET framework 4.0 & silverlight enum.getvalues work, the code I used is ---> enum.GetValues(typeof(enum))

@Yahoo Serious 2018-07-27 14:59:35

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

@Mallox 2010-07-07 13:37:41

My solution works in .NET Compact Framework (3.5) and supports type checking at compile time:

public static List<T> GetEnumValues<T>() where T : new() {
    T valueType = new T();
    return typeof(T).GetFields()
        .Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
        .Distinct()
        .ToList();
}

public static List<String> GetEnumNames<T>() {
    return typeof (T).GetFields()
        .Select(info => info.Name)
        .Distinct()
        .ToList();
}
  • If anyone knows how to get rid of the T valueType = new T(), I'd be happy to see a solution.

A call would look like this:

List<MyEnum> result = Utils.GetEnumValues<MyEnum>();

@Oliver 2010-07-07 14:17:17

what about using T valueType = default(T)?

@Mallox 2010-07-08 06:48:46

Great, I didn't even know that keyword. Always nice to learn something new. Thank you! Does it always return a reference to the same object, or does it create a new instance each time the default statement is called? I haven't found anything on the net about this so far, but if it creates a new instance every time, it kind of defeats the purpose I was looking for (having a one-liner ^^).

@Mallox 2011-06-28 15:04:18

Wouldn't this create a new instance for every iteration over the enumeration?

@nawfal 2014-01-30 04:47:52

-1 for "supports type checking at compile time:". What type checking? This would work for any new() T. Also, you dont need new T() at all, you can select just the static fields alone and do .GetValue(null). See Aubrey's answer.

@Mallox 2015-06-22 18:47:18

Type checking at compile time refers to the return value of the function, which in this case will throw an error if you're trying to assign the enum to a list of a different type. Some of the solutions here return generics which will only fail during runtime.

@Jack 2015-12-16 18:35:42

@Mallox Could you pls give an example for binding this enum values to a DropDownList in MVC?

@Mallox 2015-12-18 17:10:48

@Christof Sorry but the last time I used C# was probably in 2010.

@Yahoo Serious 2018-07-27 14:59:01

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

@bob 2009-06-03 12:03:51

I made some extensions for easy enum usage. Maybe someone can use it...

public static class EnumExtensions
{
    /// <summary>
    /// Gets all items for an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>(this Enum value)
    {
        foreach (object item in Enum.GetValues(typeof(T)))
        {
            yield return (T)item;
        }
    }

    /// <summary>
    /// Gets all items for an enum type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>() where T : struct
    {
        foreach (object item in Enum.GetValues(typeof(T)))
        {
            yield return (T)item;
        }
    }

    /// <summary>
    /// Gets all combined items from an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    /// <example>
    /// Displays ValueA and ValueB.
    /// <code>
    /// EnumExample dummy = EnumExample.Combi;
    /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
    /// {
    ///    Console.WriteLine(item);
    /// }
    /// </code>
    /// </example>
    public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
    {
        int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

        foreach (object item in Enum.GetValues(typeof(T)))
        {
            int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);

            if (itemAsInt == (valueAsInt & itemAsInt))
            {
                yield return (T)item;
            }
        }
    }

    /// <summary>
    /// Determines whether the enum value contains a specific value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <param name="request">The request.</param>
    /// <returns>
    ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
    /// </returns>
    /// <example>
    /// <code>
    /// EnumExample dummy = EnumExample.Combi;
    /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
    /// {
    ///     Console.WriteLine("dummy contains EnumExample.ValueA");
    /// }
    /// </code>
    /// </example>
    public static bool Contains<T>(this Enum value, T request)
    {
        int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
        int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);

        if (requestAsInt == (valueAsInt & requestAsInt))
        {
            return true;
        }

        return false;
    }
}

The enum itself must be decorated with the FlagsAttribute:

[Flags]
public enum EnumExample
{
    ValueA = 1,
    ValueB = 2,
    ValueC = 4,
    ValueD = 8,
    Combi = ValueA | ValueB
}

@Leyu 2010-06-22 09:29:29

A one liner for the first extension method; it's no more lazy. return Enum.GetValues(typeof(T)).Cast<T>();

@jpierson 2011-01-10 22:38:58

Alternatively you could use OfType too: Enum.GetValues(typeof(T)).OfType<T>(). It's too bad there is not a generic version of GetValues<T>() then it would be even more slick.

@Tomas 2013-02-12 08:01:30

Maybe someone could show how to use these extensions? The compiler do not show extension methods on enum EnumExample.

@bob 2013-02-15 11:24:55

@Tomas did you put the extensions in another namespace? Did you add the correct using statement?

@nawfal 2013-08-12 15:23:13

@Leyu why is it not lazy?

@Ashwini Verma 2013-09-23 13:01:07

can anyone add example how to utilize those functions?

@Krishna 2013-10-22 06:55:57

+1 for reusable code: examples - save these extension methods in a library and reference it [Flags]public enum mytypes{name1, name2 }; List<string> myTypeNames = mytypes.GetAllItems();

@Jack 2015-12-16 18:36:32

@bob What about binding this enum values to a DropDownList in MVC?

@bob 2016-01-18 20:51:07

@Yahoo Serious 2018-07-27 15:00:45

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

@Erçin Dedeoğlu 2019-11-21 12:52:15

LINQ Generic Way:

    public static Dictionary<int, string> ToList<T>() where T : struct =>
        ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());

Usage:

        var enums = ToList<Enum>();

@jop 2008-09-19 20:37:18

foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}

Note: The cast to (Suit[]) is not strictly necessary, but it does make the code 0.5 ns faster.

@Jessy 2012-06-17 03:50:38

This doesn't work if you have duplicate values in the enumerator list.

@BrainSlugs83 2013-08-13 02:05:09

@Jessy if you need all the names (including the ones with duplicate values), maybe try Enum.GetNames in conjunction with Enum.Parse. It's going to be a little slow though, I recommend doing it once during initialization (or the first time it's needed) and caching the results into an array.

@Giacomo Tagliabue 2013-10-17 05:50:55

I just want to point out that this, unfortunately won't work in silverlight, since the silverlight library don't comprise enum.GetValues. You have to use reflection in this case.

@nawfal 2013-11-07 09:25:53

@Jessy this does work in case of duplicate situations like enum E {A = 0, B = 0}. Enum.GetValues results in two values being returned, though they are the same. E.A == E.B is true, so there is not distinction. If you want individual names, then you should look for Enum.GetNames.

@Jeppe Stig Nielsen 2014-06-12 08:46:39

Then if you have duplicates/synonyms in your enum, and you want the other behavior, you can use Linq's Distinct extension (since .NET 3.5), so foreach (var suit in ((Suit[])Enum.GetValues(typeof(Suit))).Distinct()) { }.

@jpmc26 2016-01-08 22:57:08

I made the mistake of trying to use var for the type. The compiler will make the variable an Object instead of the enum. List the enum type explicitly.

@marbel82 2017-06-09 12:14:33

When I add the cast (Suit[]), my code run 1,6 times faster. Try it yourself. I tested an empty foreach with StopWatch. for (int i = 0; i < 1000000; i++) foreach (Suit suit in (Suit[])Enum.GetValues(typeof(Suit))) {}

@Ian Warburton 2018-06-13 12:39:47

@jpmc26 Can you (or anyone) explain why the compiler makes the variable an object?

@jpmc26 2018-06-13 13:21:00

@IanWarburton Documentation is your friend. Look at the return type and then the type of the index access.

@marbel82 2018-06-20 21:31:49

@BartoszKP I ran your code and I found a mistake (answered here). I improved my tests using the BenchmarkDotNet benchmark.

@BartoszKP 2018-06-21 09:05:13

@marbel82 Well done, thanks! This really qualifies as a separate Q&A (you can self-answer). Thanks for letting me learn something, this is very interesting indeed. I've reverted my edit as it looks that it's true - the version with the cast consistently produces faster code. Although IMHO this still qualifies as a micro-optimization that will make sense only in very specific cases.

@rlv-dan 2019-11-21 11:45:10

If you have:

enum Suit
{
   Spades,
   Hearts,
   Clubs,
   Diamonds
}

This:

foreach (var e in Enum.GetValues(typeof(Suit)))
{
    Console.WriteLine(e.ToString() + " = " + (int)e);
}

Will output:

Spades = 0
Hearts = 1
Clubs = 2
Diamonds = 3

@Ekevoo 2009-09-03 18:48:59

Some versions of the .NET framework do not support Enum.GetValues. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:

public Enum[] GetValues(Enum enumeration)
{
    FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
    Enum[] enumerations = new Enum[fields.Length];

    for (var i = 0; i < fields.Length; i++)
        enumerations[i] = (Enum) fields[i].GetValue(enumeration);

    return enumerations;
}

As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.

@Eric Mickelsen 2011-01-16 22:18:16

Why not use the yield keyword here instead instantiating a list?

@nawfal 2013-11-07 09:21:54

or shorter: return type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)).Cast<Enum>();

@Gabriel GM 2014-05-23 15:16:16

@nawfal: Linq isn't available .Net CF 2.0.

@Jack 2015-12-16 18:36:54

@Ekevoo How to bind this enum values to a DropDownList in MVC?

@Emily Chen 2017-10-11 04:50:31

enum types are called "enumeration types" not because they are containers that "enumerate" values (which they aren't), but because they are defined by enumerating the possible values for a variable of that type.

(Actually, that's a bit more complicated than that - enum types are considered to have an "underlying" integer type, which means each enum value corresponds to an integer value (this is typically implicit, but can be manually specified). C# was designed in a way so that you could stuff any integer of that type into the enum variable, even if it isn't a "named" value.)

The System.Enum.GetNames method can be used to retrieve an array of strings which are the names of the enum values, as the name suggests.

EDIT: Should have suggested the System.Enum.GetValues method instead. Oops.

@Silviu Preda 2018-01-15 09:30:15

Although your answer is correct in itself, it doesn't really address the OP's original question. The GetNames method returns, indeed, a string array, but the OP requires an enumerator through the values.

@Emily Chen 2018-01-16 20:17:27

@SilviuPreda: Edited. It should have been GetValues instead of GetNames.

@Limited Atonement 2009-11-16 17:19:51

foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }

I've heard vague rumours that this is terifically slow. Anyone know? – Orion Edwards Oct 15 '08 at 1:31 7

I think caching the array would speed it up considerably. It looks like you're getting a new array (through reflection) every time. Rather:

Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums) 
{
    DoSomething(suitEnum);
}

That's at least a little faster, ja?

@Stephan Bijzitter 2015-02-23 12:57:55

The compiler should take care of this, though.

@Limited Atonement 2015-02-23 17:52:10

@StephanBijzitter Wow, you're reading pretty far down on this one :-) I agree, the compiler should make my solution unnecessary.

@mhenry1384 2018-05-08 16:14:22

This is not necessary. Looking at the compiled code in ILSpy, the compiler definitely already does this. Why is this answer upvoted at all, much less 35 times?

@Limited Atonement 2018-05-09 16:58:17

It was upvoted a long time ago. A very long time ago. I would wager that the compiler would have solved this back then, too, though. But it sure looks more performant, doesn't it? ;-)

@Ross Gatih 2015-06-28 06:12:48

This question appears in Chapter 10 of "C# Step by Step 2013"

The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):

class Pack
{
    public const int NumSuits = 4;
    public const int CardsPerSuit = 13;
    private PlayingCard[,] cardPack;

    public Pack()
    {
        this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
        for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
        {
            for (Value value = Value.Two; value <= Value.Ace; value++)
            {
                cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
            }
        }
    }
}

In this case, Suit and Value are both enumerations:

enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}

and PlayingCard is a card object with a defined Suit and Value:

class PlayingCard
{
    private readonly Suit suit;
    private readonly Value value;

    public PlayingCard(Suit s, Value v)
    {
        this.suit = s;
        this.value = v;
    }
}

@Aamir Masood 2017-02-01 09:50:41

will this work if the values in enum are not sequential?

@Termininja 2017-01-09 23:39:34

Also you can bind to the public static members of the enum directly by using reflection:

typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
    .ToList().ForEach(x => DoSomething(x.Name));

@Joshua Drake 2008-09-19 21:05:02

public void PrintAllSuits()
{
    foreach(string suit in Enum.GetNames(typeof(Suits)))
    {
        Console.WriteLine(suit);
    }
}

@Ian Boyd 2010-06-01 17:46:51

That enumerates a string, don't forget to convert those things back to an enumeration value so the enumeration can be enumerated.

@Joshua Drake 2010-06-04 15:22:08

I see from your edit that you want to actually operate on the enums themselves, the above code addressed your original post.

@Gabriel 2014-09-12 18:06:51

A simple and generic way to convert an enum to something you can interact:

public static Dictionary<int, string> ToList<T>() where T : struct
{
   return ((IEnumerable<T>)Enum
       .GetValues(typeof(T)))
       .ToDictionary(
           item => Convert.ToInt32(item),
           item => item.ToString());
}

And then:

var enums = EnumHelper.ToList<MyEnum>();

@Massimiliano Kraus 2016-10-25 13:00:14

A Dictionary is not a good idea: if you have an Enum like enum E { A = 0, B = 0 }, the 0 value is added 2 times generating an ArgumentException (you cannot add the same Key on a Dictionary 2 or more times!).

@Aluan Haddad 2017-12-11 11:53:47

Why return a Dictionary<,> from a method named ToList? Also why not return Dictionary<T, string>?

@matt burns 2014-01-20 10:37:55

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}

(The current accepted answer has a cast that I don't think is needed (although I may be wrong).)

@dmihailescu 2013-11-15 20:13:12

If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:

public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible
{
    if (typeof(T).BaseType != typeof(Enum))
    {
        throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
    }
    return Enum.GetValues(typeof(T)) as T[];
}

And you can use it like below:

static readonly YourEnum[] _values = GetEnumValues<YourEnum>();

Of course you can return IEnumerable<T>, but that buys you nothing here.

@Yahoo Serious 2018-07-27 14:57:51

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

@Mickey Perlstein 2012-07-26 09:22:23

I use ToString() then split and parse the spit array in flags.

[Flags]
public enum ABC {
   a = 1,
   b = 2,
   c = 4
};

public IEnumerable<ABC> Getselected (ABC flags)
{
   var values = flags.ToString().Split(',');
   var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
   return enums;
}

ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
   Console.WriteLine(item.ToString() + " ID=" + (int)item);
}

@Slappywag 2015-10-01 10:14:30

What if you know the type will be an enum, but you don't know what the exact type is at compile time?

public class EnumHelper
{
    public static IEnumerable<T> GetValues<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }

    public static IEnumerable getListOfEnum(Type type)
    {
        MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
        return (IEnumerable)getValuesMethod.Invoke(null, null);
    }
}

The method getListOfEnum uses reflection to take any enum type and returns an IEnumerable of all enum values.

Usage:

Type myType = someEnumValue.GetType();

IEnumerable resultEnumerable = getListOfEnum(myType);

foreach (var item in resultEnumerable)
{
    Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}

@Haacked 2008-09-19 20:39:39

It looks to me like you really want to print out the names of each enum, rather than the values. In which case Enum.GetNames() seems to be the right approach.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (string name in Enum.GetNames(typeof(Suits)))
    {
        System.Console.WriteLine(name);
    }
}

By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.

I would use Enum.GetValues(typeof(Suit)) instead.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (var suit in Enum.GetValues(typeof(Suits)))
    {
        System.Console.WriteLine(suit.ToString());
    }
}

@AndruWitta 2018-09-09 02:11:27

VB Syntax here: link

@Barabas 2019-06-24 12:57:58

I took your version with a small following changes from my side: Enum.GetValues(typeof(Suits)).OfType<Suits>().ToArray(). In that case I can iterate array of Suits enum items, not strings.

@Tom Carr 2008-09-19 20:37:17

I think you can use

Enum.GetNames(Suit)

@Ian Boyd 2008-09-22 14:43:50

Enum.GetValues(Suits)

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How to cast int to enum?

  • 2008-08-27 03:58:21
  • lomaxx
  • 1307076 View
  • 3076 Score
  • 27 Answer
  • Tags:   c# enums casting int

27 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 1080440 View
  • 1921 Score
  • 27 Answer
  • Tags:   java enums

37 Answered Questions

[SOLVED] PHP and Enumerations

  • 2008-10-31 18:51:14
  • Henrik Paul
  • 471493 View
  • 1121 Score
  • 37 Answer
  • Tags:   php enumeration

39 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

27 Answered Questions

[SOLVED] Get int value from enum in C#

  • 2009-06-03 06:46:39
  • jim
  • 1449194 View
  • 1739 Score
  • 27 Answer
  • Tags:   c# enums casting int

14 Answered Questions

[SOLVED] Comparing Java enum members: == or equals()?

  • 2009-11-17 17:26:27
  • Matt Ball
  • 634096 View
  • 1668 Score
  • 14 Answer
  • Tags:   java enums

21 Answered Questions

[SOLVED] Create Generic method constraining T to an Enum

11 Answered Questions

[SOLVED] What does the [Flags] Enum Attribute mean in C#?

  • 2008-08-12 04:09:16
  • Brian Leahy
  • 464625 View
  • 1402 Score
  • 11 Answer
  • Tags:   c# enums flags

Sponsored Content