Skip to content

CA2021: false positive with ValueType and Enum #7031

Open
@MrJul

Description

Analyzer

Diagnostic ID: CA2021 (no documentation yet): Type 'U' is incompatible with type 'T' and cast attempts will throw InvalidCastException at runtime

Analyzer source

SDK: Built-in CA analyzers in .NET 8 SDK
Version: 8.0.100

Describe the bug

CA2021 incorrectly triggers when casting ValueType to a T : struct, and Enum to a T : struct, Enum.

Steps To Reproduce

public static IEnumerable<T> CastEnums<T>(IEnumerable<Enum> values) where T : struct, Enum
    => values.Cast<T>(); // CA2021

public static IEnumerable<T> CastValueTypes<T>(IEnumerable<ValueType> values) where T : struct
    => values.Cast<T>(); // CA2021

Expected behavior

No warnings.

Actual behavior

CA2021 warnings in both Cast<T> calls.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions