I have some async code that I would like to add a CancellationToken to. However, there are many implementations where this is not needed so I would like to have a default parameter - perhaps CancellationToken.None. However,
Task<x> DoStuff(...., CancellationToken ct = null)
yields
A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'System.Threading.CancellationToken'
and
Task<x> DoStuff(...., CancellationToken ct = CancellationToken.None)
Default parameter value for 'ct' must be a compile-time constant
Is there any way to have a default value for CancellationToken?
It turns out that the following works:
which, according to the documentation, is interpreted the same as
CancellationToken.None
:Tofutim's answer is one way, but from the comments I see that people have issues with it.
In that case, I did suggest that one can have a method as follows:
and overload it as:
This compiles, because the value of
CancellationToken.None
is not required at compile time.Unfortunately, this is not possible, as
CancellationToken.None
is not a compile time constant, which is a requirement for default values in optional arguments.You can provide the same effect, however, by making an overloaded method instead of trying to use default parameters:
Here are several solutions, in descending order of general goodness:
1. Using
default(CancellationToken)
as default value:Semantically,
CancellationToken.None
would be the ideal candidate for the default, but cannot be used as such because it isn't a compile-time constant.default(CancellationToken)
is the next best thing because it is a compile-time constant and officially documented to be equivalent toCancellationToken.None
.2. Providing a method overload without a
CancellationToken
parameter:Or, if you prefer method overloads over optional parameters (see this and this question on that topic):
For interface methods, the same can be achieved using extension methods:
This results in a slimmer interface and spares implementers from explicitly writing the forwarding method overload.
3. Making the parameter nullable and using
null
as default value:I like this solution least because nullable types come with a small runtime overhead, and references to the cancellation token become more verbose because of the null coalescing operator
??
.Another option is to use a
Nullable<CancellationToken>
parameter, default it tonull
, and deal with it inside the method: