Posts
114
Comments
126
Trackbacks
10
December 2007 Entries
Enum.GetValues and Enum.GetNames return arrays sorted by value

If you ran this code:

private enum FieldWidths
{
   CustomerNumber = 5,
   OrderNumber = 10,
   City = 30,
   State = 2,
   Zip = 11    
}
. . .
int[] vals = (int[])Enum.GetValues(typeof(FieldWidths));
string[] names = Enum.GetNames(typeof(FieldWidths));

...you might expect (I did, anyway) that the resulting arrays would look like this:

vals: 5, 10, 30, 2, 11

names: "CustomerNumber", "OrderNumber", "City", "State", "Zip"

What you would get, though, is:

vals: 2, 5, 10, 11, 30

names: "State", "CustomerNumber", "OrderNumber", "Zip", "City"

...because the arrays returned by Enum.GetValues and Enum.GetNames are sorted by the values in the enumeration.

I "reflectored" a bit, and there doesn't seem to be a way to get the values from an enum in the order that they were specified, so I'll stop trying to do that.

Posted On Tuesday, December 18, 2007 8:13 AM | Comments (1)
Tag Cloud