Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.GetNames() results in unexpected order with negative enum constants

Tags:

c#

.net

enums

I have the following enum definition (in C#):

public enum ELogLevel
{
    General = -1,  // Should only be used in drop-down box in Merlinia Administrator log settings
    All = 0,       // Should not be used as a level, only as a threshold, effectively same as Trace
    Trace = 1,
    Debug = 2,
    Info = 3,
    Warn = 4,
    Error = 5,
    Fatal = 6,
    Off = 7        // Should not be used as a level, only as a threshold
}

Now, when I do an Enum.GetNames() on this type I get a string array with 9 elements as expected, but the order is All, Trace, ... , Off, General, which is not what I was expecting.

Here's the MSDN documentation for Enum.GetNames():

"Remarks: The elements of the return value array are sorted by the values of the enumerated constants."

What's going on here? I can change my program to take this "functionality" into account, but I'd kind of like to know why .NET is doing what it's doing.

like image 316
RenniePet Avatar asked Jul 25 '11 16:07

RenniePet


2 Answers

This is a known bug with both GetNames() and GetValues() that was reported here, but ended up getting closed as won't fix:

Yes, this method indeed has a bug where it returns the array of enum values sorted as unsigned-types (-2 is 0xFFFFFFFE and -1 is 0xFFFFFFFF in two's complement, that's why they are showing up at the end of the list) instead of returning values sorted by their signed-types.

Unfortunately, we cannot change the sort order of GetValues because we will break all existing .NET programs that have been written to depend on the current sorting behavior [...]

Looks like you'll have to reorder the values yourself.

like image 68
BoltClock Avatar answered Oct 05 '22 07:10

BoltClock


Depending on how the sorting occurs, it may be that it is sorting the values as if they were unsigned, in which case, -1 = 0xffffffff, which is of course greater than 7.

like image 30
Iridium Avatar answered Oct 05 '22 06:10

Iridium