Home >Backend Development >C++ >Why Can C# Enums Have Non-Unique Integer Values, and When Should I Avoid This?

Why Can C# Enums Have Non-Unique Integer Values, and When Should I Avoid This?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 01:19:11537browse

Why Can C# Enums Have Non-Unique Integer Values, and When Should I Avoid This?

Non-Unique Enum Values

Question:

Why does C# allow multiple enum values to be assigned the same underlying integer value? Is it safe to use enums for this purpose, or should structs be used instead?

Answer:

Contrary to popular belief, an enum in C# is not a special type but a struct that derives from System.Enum. When you declare an enum, the compiler generates a struct with named constants for the enum values.

Your enum definition:

public enum Color
{
    Red = 1,
    Blue = 1,
    Green = 1
}

Is translated into:

public struct Color : System.Enum
{
    public const int Red = 1;
    public const int Blue = 1;
    public const int Green = 1;
}

Since structs can have multiple constants with the same value, it is possible to define enums with non-unique values. However, this can lead to inconsistencies when converting to enums:

Color color1 = (Color)1; // Returns Red
Color color2 = (Color)Enum.Parse(typeof(Color), "1"); // Also returns Red

The comparison Color.Red == Color.Green will also evaluate to true, which can be confusing.

While it is legal to use enums with non-unique values, it is recommended to only use them when it makes sense. If you need unique values, consider using a struct or a Dictionary instead.

The above is the detailed content of Why Can C# Enums Have Non-Unique Integer Values, and When Should I Avoid This?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn