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?

3
  • 1
    read this stackoverflow.com/a/8043127/1714342 and this stackoverflow.com/a/8043148/1714342 Commented Jul 9, 2013 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?? Commented Jul 9, 2013 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. Commented Jul 9, 2013 at 13:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Before downvoters - Original question asked why can enums have same values, doesnt suit new edit though
Ok, I suppose it makes sense in some cases to have multiple enum values with the same id.
It also works to define Man = 1, Woman = 0, Lady = Woman, Boy = Man, Girl = Woman.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.