Yes, two enum names can have the same value in many programming languages, including C, C++, and C#. This is legal and sometimes intentional, though it comes with important caveats about uniqueness and readability.
What an Enum Actually Is
An enumeration (enum) is a named set of integral constants. In languages like C and C++, an enum is essentially a way to give readable names to a set of integer values. The compiler assigns each enumerator an underlying integer, either explicitly or by incrementing from the previous one. In C# and Java, enums are more structured types, but the underlying idea is similar: each member has a numeric value.
Because the numeric value is what the compiler stores, nothing inherently prevents two different names from mapping to the same number. The language specification may or may not allow it, but in practice, most mainstream languages permit it.
Language-by-Language Rules
The legality and behavior of duplicate enum values vary by language. Here is a summary of common languages:
- C and C++: Duplicate values are allowed. The enumerators are just integer constants; two names can have the same value. This is often used for aliases or backward compatibility.
- C#: Duplicate values are allowed. The compiler does not require uniqueness. However, methods like
Enum.GetNamemay return only one of the names for a given value, andEnum.ToStringmay pick one arbitrarily. - Java: Enum constants are objects, and each constant is unique. You cannot assign the same ordinal to two constants directly, but you can have two constants with the same associated field value if you design it that way. The enum itself does not have duplicate numeric values unless you explicitly store them in a field.
- Python: The
enummodule allows aliases: if two members have the same value, the second becomes an alias for the first. Iteration over the enum yields only canonical members, but aliases are accessible by name. - TypeScript: Numeric enums allow duplicate values. String enums do not allow duplicates because each member must have a unique string value.
- Swift: Enums with raw values require unique raw values; duplicate raw values cause a compile-time error.
- Rust: Enums are discriminated unions; each variant is distinct, and there is no concept of assigning the same discriminant unless you use explicit
reprattributes, which can lead to undefined behavior if duplicated.
So the answer depends on the language, but in the most common systems languages (C, C++, C#), duplicate values are permitted.
Why Would You Want Duplicate Values?
There are several legitimate reasons to give two enum names the same value:
- Aliases for readability: You might want a descriptive name and a short name for the same concept, e.g.,
Color.RedandColor.Crimsonboth mapping to 0xFF0000. - Backward compatibility: When renaming an enum member, you can keep the old name as an alias to avoid breaking existing code.
- Semantic grouping: Two different names might represent the same underlying state but be used in different contexts. For example,
Status.ActiveandStatus.Enabledcould both be 1. - Interop with external systems: When mapping to a protocol or file format that uses the same code for multiple meanings, aliases can make the code clearer.
However, duplicates can also be a source of bugs, so they should be used deliberately.
Common Problems and Pitfalls
Duplicate enum values can cause subtle issues, especially when converting between names and values.
- Reverse mapping ambiguity: In C#,
Enum.GetName(typeof(MyEnum), 1)returns only one of the names that map to 1. Which one is returned is not guaranteed and may vary between runtime versions. Similarly,Enum.ToString()on a value may pick an arbitrary name. - Switch statements: In C and C++, a switch on an enum with duplicate case values will cause a compile error if you try to handle both names separately, because the case labels must be unique. You can only handle the value once.
- Serialization: When serializing enums by name, duplicates are fine, but when serializing by value, deserialization may pick the wrong name if the serializer assumes uniqueness.
- Comparison and equality: Two enum members with the same value are equal, which may be surprising if you expect them to be distinct. This can affect dictionary keys, sets, and comparisons.
- Flags enums: In bitmask enums, duplicate values are almost always a mistake, as they break the ability to combine flags uniquely.
To avoid these issues, document any intentional aliases and avoid relying on name lookup for duplicated values.
How to Choose: Aliases vs. Separate Enums
If you need two names for the same concept, consider whether an alias is the right tool. Here are some factors to weigh:
- Use an alias when the two names are truly synonymous and you want to avoid duplicating logic. For example,
MaximumandMax. - Use separate enums when the concepts are distinct even if they share a numeric value. For instance, a
Colorenum and aTrafficLightenum might both use 0 for red, but they are different types and should not be mixed. - Use a class or struct with static readonly fields if you need more control over uniqueness and behavior, as in Java or C# before enums were enhanced.
- Avoid duplicates in flags enums unless you have a very specific reason and understand the consequences.
In general, prefer clarity: if a duplicate value would confuse a reader, it is probably better to refactor.
Practical Examples
Here are concrete examples in different languages to illustrate how duplicate enum values work.
C:
enum Color {
RED = 1,
CRIMSON = 1, // alias for RED
GREEN = 2
};
This compiles fine. RED and CRIMSON are both 1. A switch statement cannot have separate cases for both.
C#:
enum Status {
Active = 1,
Enabled = 1,
Disabled = 0
}
This compiles. Status.Active == Status.Enabled is true. Status.Active.ToString() might return "Active" or "Enabled" depending on the runtime.
Python:
from enum import Enum
class Color(Enum):
RED = 1
CRIMSON = 1 # alias for RED
GREEN = 2
Here, Color.CRIMSON is an alias for Color.RED. Iterating over Color yields only RED and GREEN.
TypeScript:
enum Color {
Red = 1,
Crimson = 1,
Green = 2
}
This is allowed. However, the reverse mapping Color[1] will be "Crimson" because the last assignment wins.
Frequently Asked Questions
Can two enum names have the same value in C#?
Yes, C# allows duplicate enum values. The compiler does not enforce uniqueness. However, methods like Enum.GetName and Enum.ToString may return only one of the names, and which one is not guaranteed.
Is it a compile error to have duplicate enum values in C++?
No, it is not a compile error. C++ allows multiple enumerators with the same value. The only restriction is that you cannot use both as case labels in the same switch statement, because case values must be unique.
What happens if I serialize an enum with duplicate values?
If you serialize by name, the name is preserved. If you serialize by numeric value, deserialization may map the value back to a different name than the original, depending on the serializer and language. This can lead to data corruption if the names have different meanings.
Are duplicate enum values allowed in Java?
Java enums are different: each enum constant is a unique object, and you cannot assign the same ordinal to two constants. However, you can have two constants with the same value in a custom field, but they remain distinct objects.
Should I use duplicate enum values for aliases?
It can be acceptable for simple aliases, but be aware of the pitfalls with reverse mapping and switch statements. Document the alias clearly and avoid relying on name lookup for duplicated values.
Do duplicate enum values affect performance?
No, duplicate values do not affect runtime performance. The underlying representation is still an integer, and comparisons are just integer comparisons.