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
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
There is currently no way to detect or prevent multiple identical enum values in an enum.
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.
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()); }
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With