Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent duplicate values in enum?

Tags:

c#

.net

enums

I wonder is there a way to prevent an enum with duplicate keys to compile?

For instance this enum below will compile

public enum EDuplicates
{
    Unique,
    Duplicate = 0,
    Keys = 1,
    Compilation = 1
}

Although this code

Console.WriteLine(EDuplicates.Unique);
Console.WriteLine(EDuplicates.Duplicate);
Console.WriteLine(EDuplicates.Keys);
Console.WriteLine(EDuplicates.Compilation);

Will print

Duplicate
Duplicate
Keys
Keys
like image 200
zzandy Avatar asked Sep 15 '09 07:09

zzandy


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Do enum values have to be unique?

Show activity on this post. I also found the same idea on this question: Two enums have some elements in common, why does this produce an error? Enum names are in global scope, they need to be unique.

Can enum have duplicate values C++?

There is currently no way to detect or prevent multiple identical enum values in an enum.

Can enums have the same value C#?

Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition. But since the enum does not have unique values you might have an issue when converting into this enum.


3 Answers

Here's a simple unit test that checks it, should be a bit faster:

[TestMethod] public void Test() {   var enums = (myEnum[])Enum.GetValues(typeof(myEnum));   Assert.IsTrue(enums.Count() == enums.Distinct().Count()); } 
like image 91
Carra Avatar answered Oct 13 '22 23:10

Carra


This isn't prohibited by the language specification, so any conformant C# compiler should allow it. You could always adapt the Mono compiler to forbid it - but frankly it would be simpler to write a unit test to scan your assemblies for enums and enforce it that way.

like image 35
Jon Skeet Avatar answered Oct 14 '22 01:10

Jon Skeet


Unit test that checks enum and shows which particular enum values has duplicates:

[Fact]
public void MyEnumTest()
{
    var values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
    var duplicateValues = values.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
    Assert.True(duplicateValues.Length == 0, "MyEnum has duplicate values for: " + string.Join(", ", duplicateValues));
}
like image 44
Vlad Rudenko Avatar answered Oct 14 '22 00:10

Vlad Rudenko