Skip to content

Potential dangers with enum #39809

@The-Futurist

Description

@The-Futurist

Type of issue

Missing information

Description

I think it would be helpful to explicitly state that zero is treated in a special way when using and enum in C#. I did some refactoring and was surprised to find this

image

Also, this code generates no compiler warning or anything yet clearly returns an invalid enum value:

namespace ConsoleApp5
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var temp_1 = GetValue(0);
        }

        public static GpioPort GetValue(GpioPort X)
        {
            return X;
        }
    }

    public enum GpioPort
    {
        GpioA = 1,
        GpioB,
        GpioC,
        GpioD,
        GpioE,
        GpioF,
        GpioG,
        GpioH,
        GpioI,
        GpioJ,
    }
}

This was also totally surprising to me:

    internal class Program
    {
        private const int X = 0;
        static void Main(string[] args)
        {
            GpioPort temp_1 = GetValue(X);
        }

        public static GpioPort GetValue(GpioPort X)
        {
            return X;
        }
    }

    public enum GpioPort
    {
        GpioA = 1,
        GpioB,
        GpioC,
        GpioD,
        GpioE,
        GpioF,
        GpioG,
        GpioH,
        GpioI,
        GpioJ,
    }

I understand there are historic reasons and backward compatibility issues behind this, but it would be better to mention this to developers, so they can at least be aware of the risks.

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/language-reference/builtin-types/enum.md

Document Version Independent Id

9d67fd2d-bfaa-7af4-a8d9-fd2a84aecd15

Article author

@BillWagner

Metadata

  • ID: 248858d2-39c9-ff54-a396-5e7b4d79b640
  • Service: dotnet-csharp
  • Sub-service: lang-reference

Associated WorkItem - 479053

Metadata

Metadata

Labels

📌 seQUESTeredIdentifies that an issue has been imported into Quest.dotnet-csharp/svclang-reference/subsvcokr-qualityContent-quality KR: Concerns article defects (bugs), freshness, or build warnings.

Type

No type

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions