Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Enum.ToString() not return the correct enum name?

Tags:

c#

.net

enums

I'm working with an external library that has an enum. There are some members of this enum that, when you call ToString() on them, return the name of a different member of the enum.

Console.WriteLine("TOKEN_RIGHT = {0}", Tokens.TOKEN_RIGHT.ToString());  //prints TOKEN_OUTER
Console.WriteLine("TOKEN_FROM = {0}", Tokens.TOKEN_FROM.ToString());  //prints TOKEN_FROM
Console.WriteLine("TOKEN_OUTER = {0}", Tokens.TOKEN_OUTER.ToString());  //prints TOKEN_FULL

I know that when two enum members have the same numerical value, you can get behavior like this, but I know, from decompilation and checking the values at run-time, that each member in the enum has a unique value.

Here's a snippet of the enum's definition (generated by dotPeek):

public enum Tokens
{

    TOKEN_OR = 134,
    TOKEN_AND = 135,
    TOKEN_NOT = 136,
    TOKEN_DOUBLECOLON = 137,
    TOKEN_ELSE = 138,
    TOKEN_WITH = 139,
    TOKEN_WITH_CHECK = 140,
    TOKEN_GRANT = 141,
    TOKEN_CREATE = 142,
    TOKEN_DENY = 143,
    TOKEN_DROP = 144,
    TOKEN_ADD = 145,
    TOKEN_SET = 146,
    TOKEN_REVOKE = 147,
    TOKEN_CROSS = 148,
    TOKEN_FULL = 149,
    TOKEN_INNER = 150,
    TOKEN_OUTER = 151,
    TOKEN_LEFT = 152,
    TOKEN_RIGHT = 153,
    TOKEN_UNION = 154,
    TOKEN_JOIN = 155,
    TOKEN_PIVOT = 156,
    TOKEN_UNPIVOT = 157,
    TOKEN_FROM = 242,
}

Why is this happening? Is there something I'm doing wrong, or is this just another one of those fun quirks of enums in .NET? If the latter, is there a workaround for it?

(For what it's worth, Tokens is part of of the Microsoft.SqlServer.Management.SqlParser.Parser namespace in .NET.)

like image 785
nateirvin Avatar asked May 08 '14 19:05

nateirvin


2 Answers

You are looking at two different versions of the assembly.

Your code (at design/compile time) is referencing a newer version (since you're able to use TOKEN_FROM yet when you inspect the DLL with dotPeek, it's not there). However, the assembly loaded at runtime is an older version with different underlying values thus mismatching the names.

You'll have to investigate how it is you're referencing mismatched DLLs. It could be the installed framework on the executing machine, or perhaps you have projects in the same solution referencing different versions, or perhaps some other reason (it's not possible to determine from the information you have provided).

Once you resolve why you're referencing two different versions and unify it to a single assembly version, the Enum.ToString() result should be as you expect it.

like image 155
Chris Sinclair Avatar answered Nov 10 '22 18:11

Chris Sinclair


I suggest probe:

Console.WriteLine("TOKEN_RIGHT = {0}", Tokens.TOKEN_RIGHT.ToString("F"));

and so on

like image 1
Pablo Fébolo Avatar answered Nov 10 '22 19:11

Pablo Fébolo