Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly identifying enums with same underlying value

Tags:

c#

enums

Assume I have this enum defined, where several members have the same underlying value:

enum Number
{
  One = 1,
  Eins = 1,
  Uno = 1
}

According to MSDN documentation:

If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.

So for example,

var number = Number.One;
Console.WriteLine(number);

gives me the following output:

Eins

Printing all enum members,

Console.WriteLine($"{Number.One} {Number.Eins} {Number.Uno}");

yields the following output:

Eins Eins Eins

However, taking the nameof of each member,

Console.WriteLine($"{nameof(Number.One)} {nameof(Number.Eins)} {nameof(Number.Uno)}");

gives the following result:

One Eins Uno

So apparently the enum members are separable. Can I take advantage of this separation, i.e. is there any way I can assign a specific Number member to a variable and consistently have that same member returned whenever the variable is accessed?

like image 221
Anders Gustafsson Avatar asked Apr 05 '17 10:04

Anders Gustafsson


1 Answers

So apparently the enum members are separable

Well, that's not entirely true... They are only separable at compile time.

You see, nameof is actually an expression evaluated at compile time. It is a constant expression. This can be proved by assigning a nameof expression to a const:

const string a = nameof(Number.One);

It compiles.

Trying to get the string representation of a enum value using string interpolation on the other hand, is evaluated at runtime, so this does not compile:

const string a = $"{Number.One}";

At runtime, the enum cases are not separable, so the answer to:

is there any way I can assign a specific Number member to a variable and consistently have that same member returned whenever the variable is accessed?

is "no".

like image 145
Sweeper Avatar answered Sep 28 '22 06:09

Sweeper