Initial Value of an Enum

前端 未结 10 586
陌清茗
陌清茗 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: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 to match your initialization expectations. Becareful with this advice since Nullable 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");
    }
    

提交回复
热议问题