dotnet / dotnet/sdk

CA2016 does not fire for methods with separate overloads

Open
#52,811 0 comments 0 reactions 0 assignees View on GitHub
Area-Microsoft.CodeAnalysis.NetAnalyzers untriaged
Dominant language
C#
Stars
3.2k
Forks
1.3k
PR merge metrics
PR metrics pending

Description

### Describe the bug
CA2016 (Forward the CancellationToken parameter to methods that take one) does not fire when the invoked method has separate overloads with and without `CancellationToken`. It only fires when the method uses a default parameter (CancellationToken cancellationToken = default).

According to the [documentation](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2016), the rule should fire when:

> [...] any of the method invocations can either accept a CancellationToken as the last parameter, **or have an overload that takes a CancellationToken as the last parameter**, then the rule suggests using that option instead to ensure that the cancellation notification gets propagated to all operations that can listen to it.

### To Reproduce

I noticed the issue when working with a solution using EF6 and EFCore. The rule would trigger for methods from EFCore, but not for EF6.

```csharp

// Methods with SEPARATE OVERLOADS (like EF6)
public static class SeparateOverloads
{
public static Task FirstAsync(this IQueryable source) => throw null!;
public static Task FirstAsync(this IQueryable source, CancellationToken cancellationToken) => throw null!;
}

// Methods with DEFAULT PARAMETER (like EFCore)
public static class DefaultParameter
{
public static Task FirstAsync(this IQueryable source, CancellationToken cancellationToken = default) => throw null!;
}

public class Test
{
// BUG: CA2016 does NOT fire (separate overloads)
public async Task TestSeparateOverloads(IQueryable query, CancellationToken cancellationToken)
{
return await SeparateOverloads.FirstAsync(query);
}

// CA2016 fires correctly (default parameter)
public async Task TestDefaultParameter(IQueryable query, CancellationToken cancellationToken)
{
return await DefaultParameter.FirstAsync(query);
}
}
```

Example project:
[repro.zip](https://github.com/user-attachments/files/25081774/repro.zip)

### Exceptions (if any)

### Further technical details
- .Net 10.0.2

details of dotnet --info

- The IDE (VS / VS Code/ VS4Mac) you're running on, and its version

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.