dotnet / dotnet/sdk

CA2021 does not detect suspicious type casts on ImmutableArray (and others)

Open
#51,130 2 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
CA2021 only considers extension methods specifically on the IEnumerable type for suspicious use of OfType/Cast. This is probably too permissive.

### To Reproduce
`Array.Empty().OfType()` will produce CA2021.

`ImmutableArray.Empty.OfType()` will not.

### Further technical details
ImmutableArray directly implements OfType (and many other linq methods). Presumably other types in the wild do also.

The analyzer [does not consider](https://github.com/dotnet/sdk/blob/f49821513314459df88302142d6fe1aabbb5e9e9/src/Microsoft.CodeAnalysis.NetAnalyzers/src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.cs#L68-L79
) types providing more specific implementations that likely have the same semantics.

The analyzer at minimum should whitelist framework types to be included in the check, and I would lightly argue that semantic equivalence should be assumed of any "linqy" method with these names.

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.