Geeks With Blogs
Brian Schroer Don't Call Me Mort!

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)); 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 .NET | Back to top

Comments on this post: Enum.GetValues and Enum.GetNames return arrays sorted by value

# re: Enum.GetValues and Enum.GetNames return arrays sorted by value
Requesting Gravatar...
This is actually what I would expect to happen. If you create an enum without explicitly giving the items values, they are incrementally assigned values starting with 0.

I've only used enums with values when they had some corresponding value outside the app I was writing. For instance, if the values were stored in a database, I would have something like this:

enum BookType {
Fiction = 0,
ScienceFiction = 2,
Biography = 3,
SelfHelp = 5

This way, in code you could just call (int)BookType.ScienceFiction and get back "2". If I need to do something like what you are doing above, I would use a struct like this:

public struct AddressFieldLengths
public static readonly int CustomerNumber = 5;
public static readonly int OrderNumber = 10;
public static readonly int City = 30;
public static readonly int State = 2;
public static readonly int Zip = 11;

I'm sure there is some purpose for those methods, but I can't come up with a good reason for them right now.
Left by Glen on Dec 27, 2007 1:43 PM

Your comment:
 (will show your gravatar)

Copyright © Brian Schroer | Powered by: