NerdyHearn
Home

IPhone SMS To Gmail

Consulting
Security Alerts

Blog
Software
Projects
Links
About
Contact

Blog
FriendFeed
Facebook
Flickr
Twitter
Toluu
Last.fm
Picasa
LinkedIn

NerdyHearn - Blog


<< Back To All Blogs

Enumerating the values of an enum in C#

Tuesday, April 7th, 2009

As easy or weird as this may sound, it is not immediately obvious of how you need to go about enumerating the values of an enum in C# so that you can list all options or operate on all the values of an enumeration.

For example, if I have an enum with 4 values, and I want to enumerate over all of them, the example would be as follows:

enum Fruit {
Apple = 1,
Orange = 2,
Banana = 11,
Tomato = 12 // Yes, it's a fruit
}

Then in CSharp, you need to do some type-casting, but you can do so with Enum.GetValues as follows:

foreach (Fruit fruit in Enum.GetValues(typeof(Fruit))) {
// do something here with fruit
// (int)fruit would give you the pure integer value
}

Pretty straight-forward, but it did stump me for a few minutes.

Enumin' Tom Out.

Tags

CSharp

Related Blogs

Reading an XML file using LINQ
Comparing XML files in C# Using Microsoft's Diff and Patch Tool
ConnectionString Switcharoo
Querying Table Entities with Microsoft Azure (And ADO.NET Data Services Framework)
Awesome .NET 4: Named and Optional Parameters for Classes and Methods

Comments

Currently no comments.

Add A Comment

Name:


URL:


Email Address: (not public, used to send notifications on further comments)


Comments:


Please enter the text from the image:



NerdyHearn - Latest tech news relating to C#, SharePoint, PHP, general development, and more. LiveNation Feed - Feeds of all your local artists, concerts, and events through your favorite RSS reader SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers Tweets2Mail - Backup and search your twitter stream from Gmail TimeSinceI - Track how long you have quit smoking, how long you have been married, or how long you have done anything.