The default value for a static property

I like C #, but why can I do:

public static bool Initialized { private set; get; } 

or that:

 public static bool Initialized = false; 

but not a combination of both on the same line?

I just need to set the level of access to my variable (private set), and I need it to be set to false at startup. I would not want to make this boring personal variable _Initialized, which will be returned by the var public receiver. I like my code to be beautiful. (NB: my variable is static, it cannot be initialized in the constructor).

thank

+41
c # properties static default
Apr 07 2018-10-10T00:
source share
4 answers

You can use a static constructor

 static MyClass() { Initialized = false; } 

However, as others have already mentioned, the default bool value will be false.

+48
Apr 7 2018-10-22T00:
source share

Since C # 6:

 public static bool Initialized { private set; get; } = false; 
+11
May 20 '15 at 1:03
source share

You can simply do:

 public static bool Initialized { private set; get; } 

Since the default bool values โ€‹โ€‹are always false, there is no need to initialize it.

If you need this to be the default by default or for more complex logic, you need to do this in a static constructor or use the support field.

As for โ€œI like my code to be beautifulโ€ - personally, for initialization without default, I think it is also โ€œbeautifulโ€:

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

This makes custom initialization very visible, which is not so bad.

+6
Apr 07 2018-10-22T00:
source share

The two blocks of code you mentioned are two different things.

The first block is an automatic change of properties . This is syntactic sugar for a complete definition of properties, which is as follows:

 private static bool _initialized; public static bool Initialized { private set { _initialized = value; } get { return _initialized; } } 

The second block of code is the static definition of the participant . If you look at the extension that I cited above, you will notice that it includes the definition of a private static member. If you want to specify an initial value, you can do it here:

 private static bool _initialized = false; public static bool Initialized { private set { _initialized = value; } get { return _initialized; } } 

The built-in property definition used was designed only to make the code shorter in the most common case. If you want to do something else, you can use the full form of the property code.

Alternatively, you can go along a completely different route and use a static constructor. (See Corey's answer )

+3
Apr 07 '10 at 22:37
source share



All Articles