Friday, December 02, 2005

Christmas Calendar 2/24

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!

No comments: