NerdyHearn
Home
Blog

Contact
Mailing List

Software

Active Directory Products
Object Compare
Permission Compare

IPhone Products
Calls To Calendar
SMS To CSV
SMS To Gmail
Voicemail To Gmail

Sites
DocuTerminal
How Long For Me
My Music To Me
SaveMySerials
TypeCount

Blog
Twitter

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

Updating an LDAP Property in C#
Good Ol Cross-Threaded Socket Action
Creating an Organizational Chart using C#: Part 1
Retrieving data from SharePoint SOAP Requests using LINQ
Code Analysis with NDepend V3

Comments

Currently no comments.

Add A Comment

Name:


URL:


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


Comments:



Enter the text above, except for the 1st and last character:


NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. DocuTerminal - Online Filing Cabinet solution. Scan, search and archive your paper documents. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers My Music To Me - Stream your subsonic music collection to your Sonos wireless system TypeCount - Count how often you type across different computers! ServrTrackr - Monitor your SSL certificates, website uptime, and DNS configurations