What happens with enum when it is not set?

c#, casting, enums

Solution

`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

- Value Types (C# Reference)

- enum (C# Reference)

- Nullable Types (C# Programming Guide)

Problem

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?

Original source