Skip to content

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

@markdchurchill

Description

@markdchurchill

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<int>().OfType<string>() will produce CA2021.

ImmutableArray<int>.Empty.OfType<string>() 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 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions