dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.27k stars 5.9k forks source link

Potential dangers with enum #39809

Open Korporal opened 8 months ago

Korporal commented 8 months ago

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

BillWagner commented 8 months ago

Thanks for pointing these out. (I thought these were covered here).

I've added this to our backlog to address when we next update this article.