default value for a static property

前端 未结 4 1834
情书的邮戳
情书的邮戳 2021-01-03 17:41

I like c#, but why can I do :

public static bool Initialized { private set; get; }

or this :

public static bool Initialized         


        
4条回答
  •  时光说笑
    2021-01-03 17:55

    You can just do:

    public static bool Initialized { private set; get; }
    

    Since bool values are always false by default, there's no need to initialize it.

    If you need this to be true by default, or to have more complex logic, you need to do this in a static constructor or use a backing field.

    As for "I like my code to be beautiful" - personally, for non-default initialization, I think this is just as "beautiful":

    private static bool initialized = true;
    public static bool Initialized { get { return initialized; } }
    

    This makes the initialization to a non default very visible, which is not a bad thing.

提交回复
热议问题