5

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?

Carra
  • 17,808
  • 7
  • 62
  • 75
  • 1
    read this http://stackoverflow.com/a/8043127/1714342 and this http://stackoverflow.com/a/8043148/1714342 – Kamil Budziewski Jul 09 '13 at 13:31
  • Because it isn't part of the specs. Also, you can do this: `var whatisthisidonteven = (TestEnum)4;` Now, which enum value is that?? –  Jul 09 '13 at 13:33
  • Thanks for the links, I'll have a look. And changed my question a bit to remove the first part of the question. – Carra Jul 09 '13 at 13:33

1 Answers1

5

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.

icemalkan
  • 61
  • 1
  • 6
  • Before downvoters - Original question asked why can enums have same values, doesnt suit new edit though – Sayse Jul 09 '13 at 13:42
  • Ok, I suppose it makes sense in some cases to have multiple enum values with the same id. – Carra Jul 09 '13 at 13:43
  • It also works to define `Man = 1, Woman = 0, Lady = Woman, Boy = Man, Girl = Woman`. – Bobson Jul 09 '13 at 14:16