ILearnable .Net

December 2, 2005

Christmas Calendar 2/24

Filed under: Uncategorized — andreakn @ 01:57

Iterating enums

it’s not trivial to iterate enums in .Net 1.1

A solution is to do the following (iterating MyEnum):
foreach(string enumstring in Enum.GetNames(typeof(MyEnum)))
{
MyEnum enumItem = Enum.Parse(typeof(MyEnum),enumstring);

}

This will only work if the enum has a different GetHashCode() for all the
items in it. Otherwise only the first item with a given hashcode will be used (multiple times).

This is due to the ridicoulus fact that Enum.Parse does not match the name given with the enum’s ToString (as one would expect) but rather matches on the hashcodes…

go figure!

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: