Initial Value of an Enum

前端 未结 10 560
陌清茗
陌清茗 2020-12-08 01:51

I have a class with a property which is an enum

The enum is

/// 
/// All available delivery actions
/// 
public enum E         


        
相关标签:
10条回答
  • 2020-12-08 02:31

    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.

    0 讨论(0)
  • 2020-12-08 02:34

    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");
    }
    
    0 讨论(0)
  • 2020-12-08 02:35

    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;
    
    0 讨论(0)
  • 2020-12-08 02:36

    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?).

    0 讨论(0)
提交回复
热议问题