Pergunta

I have the following cast:

int myInteger = (int)myItem.EnumValue;

Where the enum is:

public enum EnumValue
{
     Yes= 0,
     No = 1
}

From my observations it seems that when the EnumValue on myItem is not set, the value of EnumValue is on default set to Yes and subsequently cast to 0.

Why is the enum not null? Is my observation correct and why is it so?

Foi útil?

Solução

Enum's are value types, so just like int's and other value types, they cannot be null. Instead their default value is the equivalent of 0 (since you've assigned an enum value of Yes to 0, that's the default value in this case).

If you want a nullable enum, use Nullable<EnumValue> or EnumValue? for short.

Further Reading

Outras dicas

Because enum variable is essentially a variable of enum underlying type. By default it is integer. Integer cannot have null value.

UPDATE: Under hood enum looks like

class public auto ansi sealed EnumValue extends [mscorlib]System.Enum 
{ 
    .field public static literal EnumValue Yes = int32(0x00000000)
    .field public static literal EnumValue No = int32(0x00000001) 

    .field public specialname rtspecialname int32 value__ 
}

I.e. its a set of constants (which are inlined during compilation) and integer (by default) field which holds enum value. Thats why you can assign any integer value to variable of EnumValue type. That's why by default it has value 0. That's why it cannot be null.

Several answers suggest using a nullable enum, but you can also build similar logic into your enum without the overhead of the Nullable type:

public enum EnumValue
{
     Unknown = 0,
     Yes = 1,
     No = 2
}

Since the enum's default value is 0, the default value is Unknown. Note that the default value is zero even if you don't define a field with the value zero, like this:

public enum EnumValue
{
     Yes = 1,
     No = 2
}

Why is enum not null?

Because enum is a value type, which can never be null.

The underlying type of an enumeration is always integral. From the docs:

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int.

Since yours is based on int, the default value of the enum is the default value of an integer - which is zero.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top