Skip to content
Fix Code Error

How to enumerate an enum

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

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.

Answered By: jop

Related Articles

  • How to initialize a static array?
  • Integrating a jQuery plugin into NextJS
  • Is CSS Turing complete?
  • What does the [Flags] Enum Attribute mean in C#?
  • How does PHP 'foreach' actually work?
  • Search match multiple values in single field in…
  • Maven2: Missing artifact but jars are in place
  • How to enumerate an enum with String type?
  • Dynamically generate custom component in view with Aurelia
  • How to filter a RecyclerView with a SearchView
  • C# Public Enums in Classes
  • Java - How Can I Write My ArrayList to a file, and…
  • Vue custom directive uses the updated Dom (or $el)
  • What is a NullReferenceException, and how do I fix it?
  • What's the difference between eval, exec, and compile?
  • For-each over an array in JavaScript
  • QUnit, Sinon.js & Backbone unit test…
  • How to pass props to {this.props.children}
  • TypeScript metadata reflection references other…
  • How to loop through all enum values in C#?
  • how to fetch json data from a remote server in a…
  • error LNK2005: ✘✘✘ already defined in…
  • Compiler error: "class, interface, or enum expected"
  • data.table vs dplyr: can one do something well the…
  • Vue.JS & Spring Boot - Redirect to homepage on 404
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Why does C++ code for testing the Collatz conjecture…
  • How do I check if a type is a subtype OR the type of…
  • MySQL user DB does not have password columns -…
  • Calculate time difference in minutes in SQL Server
  • How to get the Display Name Attribute of an Enum…
  • enum to string in modern C++11 / C++14 / C++17 and…
  • What are the undocumented features and limitations…
  • C# Iterating through an enum? (Indexing a System.Array)
  • Polymer - How to data-bind paper-dropdown menu…
  • How to make Lodash orderBy to sort only the records…
  • Create a new column in pyspark dataframe by applying…
  • What is the scope of variables in JavaScript?
  • What does "Fatal error: Unexpectedly found nil while…
  • dynamic_cast and static_cast in C++
  • Ukkonen's suffix tree algorithm in plain English
  • When should static_cast, dynamic_cast, const_cast…
  • Callback functions in C++
  • Java Class.cast() vs. cast operator
  • How to download and save an image in Android
  • Typescript Symbol.species typing inference
  • Usage of __slots__?
  • How to find Control in TemplateField of GridView?
  • Why after set mapping, index return nothing?
  • Why is enum class preferred over plain enum?
  • Vue&TypeScript: how to avoid error TS2345 when…
  • Identifying and solving…
  • What is an optional value in Swift?
  • Return multiple values in JavaScript?
  • What is a typedef enum in Objective-C?
  • Javax.net.ssl.SSLHandshakeException:…
  • Extract from Union type where discriminator is also a Union
  • What's the difference between Instant and LocalDateTime?
  • Conversion failed when converting the varchar value…
  • C++ error 'Undefined reference to Class::Function()'
  • What are the new features in C++17?
  • Create Generic method constraining T to an Enum
  • What is it about Vue that enables developers to use…
  • is inaccessible due to its protection level
  • How to generate a random string of a fixed length in Go?
  • error: resource android:attr/fontVariationSettings not found
  • How to make a conditional button that changes the…
  • Where and why do I have to put the "template" and…
  • Correct format specifier to print pointer or address?
  • What is a NullPointerException, and how do I fix it?
  • jQuery pass more parameters into callback
  • What is the difference between the HashMap and Map…
  • Replacing a 32-bit loop counter with 64-bit…
  • How can I mock an ES6 module import using Jest?
  • What is and how to fix…
  • Passing parameters to Ember triggerAction which…
  • What are access specifiers? Should I inherit with…
  • Add event directive to svelte html expression?
  • Java string to date conversion
  • Mocking methods on a Vue instance during TDD
  • PHP: How to remove all non printable characters in a string?
  • Different return type for function factory typescript
  • Understanding PrimeFaces process/update and JSF…
  • Improve INSERT-per-second performance of SQLite
  • Call An Asynchronous Javascript Function Synchronously
  • run script if Date_1 > Date_2
  • What is your most productive shortcut with Vim?
  • Regular cast vs. static_cast vs. dynamic_cast
  • commandButton/commandLink/ajax action/listener…
  • Getting attributes of Enum's value
  • Create a custom callback in JavaScript
  • What does this symbol mean in JavaScript?
  • How do I display a MySQL error in PHP for a long…
  • Different Task approaches work differently
  • Does moment.js allow me to derive a timezone…
  • How can I represent an 'Enum' in Python?
  • Proper use of const for defining functions in JavaScript
  • vue v-for of typescript enum
  • How can I get the data type of a variable in C#?
  • How do you bind an Enum to a DropDownList control in…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Can’t create handler inside thread that has not called Looper.prepare()

Next Post:

Convert a string to int using sql query

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error