Fix MA0040 suggesting static, write-only, and indexer members as cancellation tokens
What
MA0040 suggested member paths that cannot be used to read a CancellationToken, and the code fix then produced code that does not compile:
class Test
{
static void A(HttpRequest request)
{
MethodWithCancellationToken();
}
static void MethodWithCancellationToken() => throw null;
static void MethodWithCancellationToken(CancellationToken cancellationToken) => throw null;
}
class HttpRequest
{
public static CancellationToken Shared { get; }
}
Expected: MA0032 (no token available). Actual: MA0040 "available tokens: request.Shared", and the fix passes request.Shared (CS0176). The same happened with:
- static fields,
- write-only properties (
public CancellationToken Token { set { } }, CS0154), - properties whose getter is not accessible from the call site (
{ private get; set; }, CS0271), - indexers (the path was
request.this[]).
Fix
When collecting the members of the variables in scope (GetMembers), the analyzer skips static members, indexers, and properties without a getter. The accessibility check of the member path now checks the getter of the properties instead of the property itself.
Tests
Added the CallingMethodWithClassThatContainsANonUsableMemberOfTypeCancellationToken_ShouldNotSuggestTheMember theory (5 cases, all failed before the fix) to UseAnOverloadThatHasCancellationTokenAnalyzerTests. The test class passes on roslyn5.9 (72/72) and roslyn4.8 (72/72).