Is default(CancellationToken) equivalent to CancellationToken.None?

大兔子大兔子 提交于 2019-12-04 23:43:52

After filing an issue with corefx, the documentation remarks have been updated to make this a guaranteed feature:

You can also use the C# default(CancellationToken) statement to create an empty cancellation token.

They are the same. Check source code

public static CancellationToken None
{
    get { return default(CancellationToken); }
}

From https://referencesource.microsoft.com/#mscorlib/system/threading/CancellationToken.cs,36b17ded8b1a228c

CancellationToken.None simply returns new CancellationToken:

public static CancellationToken None
{    
    get
    {
        return new CancellationToken();
    }
}

Thus CancellationToken is a struct, then default(CancellationToken) will return same value. C# Spec 5.2:

For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor

UPDATE: This behavior is not defined on MSDN, so you can rely only on current implementation.

default is defined for every type. It is null for reference types. It is an "empty" instance for structs, i.e. one with all properties initialized to their respective default values.

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