ITADN

Implicit conversion of integer literal 0 to enum allowed even when enum has no zero member — surprising and error-prone

#84958ClosedMatjaz-J 创建于 3 天前
Resolution-By DesignArea-Language Design
M
Matjaz-Jcommented
With help of Copilot: Repro environment • C# language version: default (current) • .NET target: any (reproducible on .NET 10) • Compiler: Roslyn (current) Minimal repro ```cs enum WeighingStatus { NotWeighing = 1, StartWeighing, RequestValue } class C { // previous declaration was: int weighingStatus; WeighingStatus weighingStatus = WeighingStatus.NotWeighing; void M() { // compiles without error weighingStatus = 0; // accidental leftover from previous int variable — very surprising } } ``` Actual behavior • The assignment weighingStatus = 0; compiles. Other integer literals (e.g. = 1) produce a compile error unless cast. The special-case implicit conversion of integer constant 0 to any enum is permitted by the language and the compiler accepts it even if the enum does not define a zero member. Expected behavior / problem • This implicit conversion is surprising and can hide bugs when code previously used an int and was later converted to an enum. It is easy to accidentally leave = 0 assignments in code and get no compile-time diagnostic, causing runtime confusion (enum value with no named member). A warning (or opt-in analyzer) when assigning the integer constant 0 to an enum that defines no zero-valued member would help catch these issues. Suggested remedies • Consider adding a compiler warning (e.g. "CSXXXX: assigning integer constant 0 to enum of type 'T' with no zero-valued member") or language/design note recommending explicit zero member Unknown = 0. Alternatively, provide an analyzer that flags implicit zero assignments to enums without a zero member.
关闭于 2 天前 2 条评论