Reputation: 33
Can somebody explain to me why they used arg1, arg2 ....
in AspNetCore.SignalR.SendAsync
method, instead of params object[] args
?
Is there a better way of doing that?
Upvotes: 3
Views: 1281
Reputation: 40928
The CancellationToken
is optional. You'll notice in the documentation that it's defined as:
System.Threading.CancellationToken cancellationToken = null
(Although in the actual code it's = default
, so I think the docs are wrong)
Optional arguments must come last.
But also, using infinite parameters with the params
keyword must also come last. So you cannot use both in the same method definition.
An alternative could have been to create the method with the CancellationToken
as the second-last parameter, and an overload without it:
public static Task SendAsync (this HubConnection hubConnection, string methodName, params object[] args) {
return SendAsync(hubConnection, methodName, default, args);
}
public static Task SendAsync (this HubConnection hubConnection, string methodName, CancellationToken cancellationToken, params object[] args) {
...
}
That effectively makes the CancellationToken
optional. However, in this specific case, it would also prevent you from sending a CancellationToken
as the first argument (in the args
array) and not in the cancellationToken
parameter, if you needed to do that for whatever reason.
But Microsoft also has the standard of putting the CancellationToken
as the last parameter in every async method they write. So they would be breaking that pattern if they did this. So they settled on only allowing 10 arguments.
Upvotes: 4
Reputation: 44600
It seems like they wanted a CancellationToken
as a last argument. This is a common practice to have it as a last argument of a method.
await SendAsync(..., arg1, arg2, arg3, cancellationToken);
await SendAsync(..., cancellationToken, arg1, arg2, arg3);
I much rather prefer the 1st line than the second one. You can only use params as a last argument of a method, which would not let them have a cancellation token as a last argument. So they decided to implement multiple overloads with different number of arguments, which allows them to put cancellationToken
as a very last argument of each overload.
Upvotes: 1