Enum 'aliasing' and ToString()

  • Thread starter Thread starter Jon Shemitz
  • Start date Start date
J

Jon Shemitz

Let's say I have an enum like

public enum Aliased {A = 0, B, C, Lowest = A, Highest = C};

and a variable

Aliased Variable = Aliased.C;

When I do Variable.ToString() in simple test code, I get "C". Yet, in
a real app, in similar code, I get the equivalent of "Highest" - ie, I
get the aliased name, not the 'primary' name.

My less important question is: Why the difference between the two? Why
isn't it ALWAYS the first defined or ALWAYS the last defined or ALWAYS
the first alphabetically?

My real question: Is there a way to control which name ToString will
use? I'd expect something like an attribute that I can apply to an
enum member

public enum Aliased
{
A = 0, B, C,
[NoName] Lowest = A,
[NoName] Highest = C
};

.... but there doesn't seem to be anything of the sort?
 
Jon Shemitz said:
Let's say I have an enum like

public enum Aliased {A = 0, B, C, Lowest = A, Highest = C};

and a variable

Aliased Variable = Aliased.C;

When I do Variable.ToString() in simple test code, I get "C". Yet, in
a real app, in similar code, I get the equivalent of "Highest" - ie, I
get the aliased name, not the 'primary' name.

My less important question is: Why the difference between the two? Why
isn't it ALWAYS the first defined or ALWAYS the last defined or ALWAYS
the first alphabetically?

I suspect it may well have something to do with hashcodes, but either
way, it's not defined.
My real question: Is there a way to control which name ToString will
use? I'd expect something like an attribute that I can apply to an
enum member

I don't believe there's any way of doing it.
 
Jon Skeet said:
[ToString is inconsistent with enum items]
Is there a way to control which name ToString will
use? I'd expect something like an attribute that I can
apply to an enum member

I don't believe there's any way of doing it.

It's not especially elegant, but as a workaround you could apply a
DescriptionAttribute to each enum element and use that description
rather than calling ToString.

P.
 
Jon Skeet said:
I suspect it may well have something to do with hashcodes, but either
way, it's not defined.

Thanks, Jon. You definitely deserve that MVP.
I don't believe there's any way of doing it.

Thanks. That's what I thought; I switched the code to put the aliases
into a second enum.
 
Back
Top