Implementing some method with parameter of type Enum as base class for all enums I was curios whether i need to check the meth’s parameter of type Enum is null.
From experience I know, that enum can’t be null, that is also confirmed by compiler: CS0037.
In the documentation for System.Enum there are sentences like:
"Enum is the base class for all enumerations in the .NET Framework"
and
"Note that in all cases, the enumeration does not explicitly inherit
from Enum; the inheritance relationship is handled implicitly by the
compiler"
What does mean "inheritance relationship is handled implicitly by the compiler" and if there is an inheritance why I can’t assign null to the derived class, but I can do it for the base class? Is it something like object and int?
enum SomeEnum { a,b,c }
void SomeMethWantsEnum(Enum someEnum)
{
if (someEnum == null) return;
var x = SomeEnum.a;
someEnum = x; //OK
someEnum = null; //OK
x = null; //Not OK, CS0037
}
>Solution :
enums are very special types very specially handled by the compiler. While it is true that they inherit from System.Enum there is another thing which is true, as docs state:
Any enumeration type also satisfies the
structconstraint, which is used to specify that a type parameter is a non-nullable value type.
So the following:
Enum x = SomeEnum.A;
Is actually a boxing operation. Check the emitted IL @sharplab, it will contain something like:
IL_0001: box SomeEnum
So you can assign null to variable of type Enum, but cant to variable of type SomeEnum. And that is the reason why you should not work explicitly with System.Enum type, in later C#/compiler versions you can work with it as generic constraint:
void SomeMethWantsEnumGen<T>(T someEnum) where T : System.Enum
{
}
But I would recommend to follow it by struct one:
void SomeMethWantsEnumGen<T>(T someEnum) where T : struct, System.Enum
{
if (someEnum == null) return; // not ok
someEnum = null; // not ok
}
What does mean "inheritance relationship is handled implicitly by the compiler"
It means that you don’t need to explicitly inherit from Enum (actually in C# you can’t do it), the compiler will do it for you:
Console.WriteLine(typeof(SomeEnum).BaseType == typeof(Enum)); // prints true
public enum SomeEnum { A,B,C }
Is it something like
objectandint?
Basically yes.
Read also: