Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# enums - Possible to have double ids [duplicate]

I just noticed that you can create something like this in C#:

enum TestEnum
{
  First = 1,
  Second = 1,
  Third = 2
}

[TestMethod]
public void Test()
{
  TestEnum test = TestEnum.First;
  var en = (TestEnum) 1;//And en is now set to First
}

We would like the enums value to be unique. Right now, I have written a unit test that checks that each value is only used once in our enum. Is there a better way to force the uniqueness?

like image 277
Carra Avatar asked Jul 09 '13 13:07

Carra


1 Answers

Well enums are used to give meaning to integers. When you say Second = 1 that doesn't make sense but think of an example like that one:

enum HumanEnum
{
    Man = 1,
    Woman = 0,
    Lady = 0,
    Boy = 1,
    Girl = 0
}

Let's say 0 and 1 represents the gender, in this way Man and Boy has the same gender value.

like image 196
icemalkan Avatar answered Sep 19 '22 12:09

icemalkan