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
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.
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 thisAlso, this code generates no compiler warning or anything yet clearly returns an invalid
enum
value:This was also totally surprising to me:
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