Home All Groups Group Topic Archive Search About

system.enum.getvalues

Author
23 Oct 2006 8:29 PM
Jeff Mason
I am observing some puzzling behavior with the GetValues method of enumerations. I
wonder if this something I just don't understand, or is this just wrong.

The documentation for the GetValues method says "The elements of the array [returned]
are sorted by the values of the enumeration constants". Further the docs state that
absent any underlying type definition of the enumeration, the type is assumed to be
int32 (a signed integer).

Consider the following code:

Public Enum MyEnum
   Entry1
   Entry2
   Entry3
End Enum

Sub DisplayValues
   For Each i As Integer In System.Enum.GetValues(GetType(MyEnum))
      Debug.WriteLine(i.ToString)
   Next
End Sub

As expected, the values displayed are 0, 1, and 2.

If I redefine the enumeration as:

Public Enum MyEnum
   Entry1 = -1
   Entry2 = 0
   Entry3 = 1
End Enum

Then the values displayed are 0, 1, -1 (!)

It seems the values are sorted as *unsigned* integers.

Thus:

Public Enum MyEnum
   Entry1 = -1
   Entry2 = -2
   Entry3 = 0
End Enum

displays 0, -2, -1 (!!)

What's going on here?

I've verified the same behavior occurs in both .NET 1.1 and 2.0.

  -- Jeff

Author
26 Oct 2006 5:37 PM
Patrick Steele
In article <4s8qj2divqifo5av7qs0klq8dubcq52***@4ax.com>,
je.ma***@comcast.net says...
> What's going on here?
>
> I've verified the same behavior occurs in both .NET 1.1 and 2.0.

Yeah -- that does look odd and doesn't match the docs.  But are you
relying on this behavior for something?

I guess I don't see it as a big deal (it's a bit of a performance hit
anyway since it uses reflection to get the values from the Enum).