I have a class with a property which is an enum
The enum is
///
/// All available delivery actions
///
public enum E
I'd suggest having a value of None = 0 as your first enum value. Make it explicit, then you know for sure what it's value is.
Enums are value types. Value types cannot be null and are initialized to 0.
Even if your enum does not have a 0, enum variables will be initialized to 0.
public enum SomeEnum
{
A = 1,
B = 2
}
(later)
SomeEnum x = default(SomeEnum);
Console.WriteLine(x);
Outputs - 0
Some answerers are advocating using Nullable<T>
to match your initialization expectations. Becareful with this advice since Nullable<T>
is still a value type and has different semantics than reference types. For example, it will never generate a null reference exception (it's not a reference).
SomeEnum? x = default(SomeEnum?);
if (x == null)
{
Console.WriteLine("It's null!");
}
if (x > SomeEnum.B)
{
}
else
{
Console.WriteLine("This runs even though you don't expect it to");
}
The traditional aproach to adding a null to values that don't generally have one is to declare your variable as a nullable type, ie:
EnumDeliveryAction? action=null;
Default value for enum
types is 0
(which is by default, the first element in the enumeration). Fields of a class will be initialized to the default value.
If you need to represent an unknown value in the enum, you can add an element Unknown
with value 0. Alternatively, you could declare the field as Nullable<MyEnum>
(MyEnum?
).