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 false positive on Enumerable.OfType<T>extension #7153

Closed
cizmiak opened this issue Jan 18, 2024 · 2 comments · Fixed by #7183
Closed

CA2021 false positive on Enumerable.OfType<T>extension #7153

cizmiak opened this issue Jan 18, 2024 · 2 comments · Fixed by #7183
Assignees
Labels
Area-Microsoft.CodeAnalysis.NetAnalyzers False_Positive A diagnostic is reported for non-problematic case help wanted The issue is up-for-grabs, and can be claimed by commenting
Milestone

Comments

@cizmiak
Copy link

cizmiak commented Jan 18, 2024

Analyzer

Diagnostic ID: CA2021: CA2021: Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types

Analyzer source

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

Describe the bug

Warning CA2021 is found on Enumerable.OfType call when T is compatible with underlining type in the enumerable collection.

Steps To Reproduce

	public static void Main()
	{
		var nodeChanges = new List<INodeUpdate<GraphNode>> { new DataNodeUpdate(new DataNode(0, 0)) };

		//warning CA2021: This call will always result in an empty sequence because type 'INodeUpdate<GraphNode>' is incompatible with type 'DataNodeUpdate'
		var nodeChangesFiltered = nodeChanges.OfType<DataNodeUpdate>();

		Debug.Assert(nodeChangesFiltered.Count() == 1);
	}

	public abstract record class GraphNode(long Id);
	public sealed record class DataNode(long Id, long Value) : GraphNode(Id);

	public interface INodeUpdate<out T>
	{
		T Updated { get; }
	}

	public abstract record class NodeUpdate<T>(T Updated) : INodeUpdate<T> where T : GraphNode;
	public sealed record class DataNodeUpdate(DataNode Updated) : NodeUpdate<DataNode>(Updated);

Expected behavior

No CA2021 warning.

Actual behavior

CA2021 warning is found.

@mavasani
Copy link
Contributor

Tagging @buyaa-n - is this related to #6457? Are the fixes in that PR part of .NET 8 SDK?

@mavasani mavasani added this to the .NET vNext milestone Jan 22, 2024
@buyaa-n
Copy link
Contributor

buyaa-n commented Feb 7, 2024

Doesn't look like it is fixed with #6457, @fowl2 could you take a look?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area-Microsoft.CodeAnalysis.NetAnalyzers False_Positive A diagnostic is reported for non-problematic case help wanted The issue is up-for-grabs, and can be claimed by commenting
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants