dotnet / roslyn-analyzers

MIT License
1.59k stars 465 forks source link

CA2021: false positive with ValueType and Enum #7031

Open MrJul opened 11 months ago

MrJul commented 11 months ago

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.

colejohnson66 commented 11 months ago

It seems the analyzer is complaining because of the struct constraint; Removing it removes the warning. Makes sense, as a struct type can't ever inherit from a class (except for when it can, here, and with ValueType).