default value for a static property

梦想的初衷 提交于 2019-11-30 16:47:05
Corey Sunwold

You could use a static constructor

static MyClass()
{
    Initialized = false;
}

However, as has been mentioned by others the default value of a bool will be false.

Since C# 6:

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

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.

Simon P Stevens

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

The first block is an auto implemented property defination. This is syntactic sugar for a full property defination which looks like this:

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

Your second block of code is a static member definition. If you look at the expansion I have given above, you'll notice that it includes a private static member definition. If you want to provide 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 inline property definition you are using was designed just to make code a bit shorter in the most common case. If you want to do anything else, you can use the full form of the property code.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!