csharplang icon indicating copy to clipboard operation
csharplang copied to clipboard

[Proposal]: Closed Enums

Open 333fred opened this issue 11 months ago • 0 comments

Closed Enums

Summary

Allow an enum type to be declared closed:

public closed enum Color
{
    Red,
    Green,
    Blue
}

This prevents creation of enum values other than the specified members.

A consuming switch expression that covers all its specified members can therefore be concluded to "exhaust" the closed enum - it does not need to provide a default case to avoid warnings:

Color color = ...;

string description = color switch
{
    Red => "red",
    Green => "green",
    Blue => "blue"
    // No warning about missing cases
};

Design meetings

  • https://github.com/dotnet/csharplang/blob/main/meetings/2022/LDM-2022-09-26.md#discriminated-unions
  • https://github.com/dotnet/csharplang/blob/main/meetings/2025/LDM-2025-06-25.md#unions
  • https://github.com/dotnet/csharplang/blob/main/meetings/2025/LDM-2025-10-01.md#closed-enums

Related Proposals

  • https://github.com/dotnet/csharplang/discussions/9010

333fred avatar Jan 06 '25 22:01 333fred