Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CA2021 Do not call Enumerable.Cast<T> or Enumerable.OfType<T> false positives #6457

Closed
buyaa-n opened this issue Jan 26, 2023 · 5 comments
Closed
Labels
Area-Microsoft.CodeAnalysis.NetAnalyzers Bug The product is not behaving according to its current intended design

Comments

@buyaa-n
Copy link
Contributor

buyaa-n commented Jan 26, 2023

Analyzer

Diagnostic ID: CA2021: Do not call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types

Analyzer source

SDK: Built-in CA analyzers in .NET 8 SDK or later

Describe the bug

Following false positives found in runtime test builds (normally we don't turn on analyzers in test projects, but this analyzer warns by default therefore failing the test builds). So, we have lowered the analyzer severity into info level until these bugs fixed. @fowl2 please let us know if you interested in fixing these, thanks!

  1. False positive with dynamic expressions:
  // Type 'int' is incompatible with type 'dynamic' and cast attempts will throw InvalidCastException at runtime
     int[] numbers = new int[] { 1, 2, 3 };
     var v = from dynamic d in numbers select (int)d;
  1. False positive with nullability annotations:
  // Type 'int' is incompatible with type 'int?' and cast attempts will throw InvalidCastException at runtime
    Enumerable.Range(1, 5).Cast<int?>();
  1. False positive with ValueTuple
  // Type '(int, int)' is incompatible with type '(int min, int max)' and cast attempts will throw InvalidCastException at runtime
    from (int min, int max) pair in new[] { (1, 2), (-10, -3) };
  1. For this one don't have a sample repro yet, check the runtime code for more details
// `Type 'System.Collections.Generic.KeyValuePair<string, System.Text.RegularExpressions.Group>' is incompatible with type 'System.Text.RegularExpressions.Group' and cast attempts will throw InvalidCastException at runtime`
     var actualSet = new HashSet<(int start, int end)>(
                match.Groups
                .Cast<Group>()
                .Select(g => (start: g.Index, end: g.Index + g.Length)));

Expected behavior

No warning

Actual behavior

Warns

Additional context

Found in: dotnet/runtime@f3bcd21

CC @fowl2 @stephentoub

@fowl2
Copy link
Contributor

fowl2 commented Jan 27, 2023

@buyaa-n I've started work on this

@hoyosjs
Copy link
Member

hoyosjs commented Mar 12, 2023

There's one other case I think this is throwing a warning where I didn't quite expect it:

        [Fact]
        public async Task CanCastReadonlyStructToInterface()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.Collections;
using System.Collections.Generic;
using System.Linq;

interface IInterface {}

readonly struct Implementation : IInterface {}

class C
{
    void M()
    {
        IEnumerable<Implementation> e = default;
        e.Cast<IInterface>();
    }
}
");
        }

The problem is

https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.cs#L318-L319

It doesn't consider interfaces on structs.

@buyaa-n
Copy link
Contributor Author

buyaa-n commented Mar 12, 2023

It doesn't consider interfaces on structs.

Right, @hoyosjs is this blocking any repo build or PR?

CC @fowl2 could you fix this?

@hoyosjs
Copy link
Member

hoyosjs commented Mar 12, 2023

I submitted the fix PR. Its not blocking. We wanted to enable the rule in a repo that's gonna be merged into another one that has the rule enabled. This flags and breaks the build. We'll update the analyzer when it becomes available.

Cc: @leculver

@buyaa-n
Copy link
Contributor Author

buyaa-n commented Mar 12, 2023

Thanks @hoyosjs, the fix merged, closing this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area-Microsoft.CodeAnalysis.NetAnalyzers Bug The product is not behaving according to its current intended design
Projects
None yet
Development

No branches or pull requests

3 participants