Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters position in methods - params VS CancellationToken

Tags:

c#

params should be the last parameter of a method => if violation, Compiler Error:
[CS0231] A params parameter must be the last parameter in a formal parameter list

CancellationToken should be the last parameter of a method => if violation, Warning CA1068: CancellationToken parameters must come last (https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1068).

When we have both, we have to privilege fixing the compiling error - put the CancellationToken before params. If we have other parameters, the most ideal one, IMO, should be:

TReturnType MyMethod(int num, string str, CancellationToken ct, params MyEnum[] myEnums);

Is this the correct way?

like image 899
yi.han Avatar asked Oct 16 '25 11:10

yi.han


1 Answers

The cancellation token parameter must come before the params parameter or you can't compile. There's no way around that.

That said, there is a better way. Avoid params in the first place. I see a few ways of doing this.

Multiple Overloads

Often you will see multiple overloads for a method instead of using params. This is usually for performance reasons, but in your case it can be to avoid the warnings and errors.

This means you'd have to come up with a reasonable number in advance, and a final overload that takes in an array or an IEnumerable<>.

TReturnType MyMethod(int num, string str, MyEnum first, CancellationToken ct);
TReturnType MyMethod(int num, string str, MyEnum first, MyEnum second, CancellationToken ct);
TReturnType MyMethod(int num, string str, MyEnum first, MyEnum second, MyEnum third, CancellationToken ct);

TReturnType MyMethod(int num, string str, MyEnum[] myEnums, CancellationToken ct);
// and/or
TReturnType MyMethod(int num, string str, IEnumerable<MyEnum> myEnums, CancellationToken ct);

Flags

If your type happens to be an enum consider making it Flags.

[Flags]
public enum MyEnum
{
    Red = 1, Green = 2, Blue = 4
};

Then you can change the signature of the method to

TReturnType MyMethod(int num, string str, MyEnum myEnums, CancellationToken ct);

and access individual flags of myEnums using HasFlag.

like image 176
Kit Avatar answered Oct 19 '25 01:10

Kit