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

Fix CA2021 false positive for generic class types #7488

Merged
merged 2 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ static bool CastWillAlwaysFail(ITypeSymbol castFrom, ITypeSymbol castTo)
return false;
}

// Most checks are better with OriginalDefinition, but keep the ones passed in around.
ITypeSymbol castFromParam = castFrom;
ITypeSymbol castToParam = castTo;

castFrom = castFrom.OriginalDefinition;
castTo = castTo.OriginalDefinition;

Expand Down Expand Up @@ -269,8 +273,8 @@ static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbo
return false;

case (TypeKind.Class, TypeKind.Class):
return !castFrom.DerivesFrom(castTo)
&& !castTo.DerivesFrom(castFrom);
return !castFromParam.DerivesFrom(castToParam)
&& !castToParam.DerivesFrom(castFromParam);

case (TypeKind.Interface, TypeKind.Class):
return castTo.IsSealed && !castTo.DerivesFrom(castFrom);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,50 @@ public sealed record class DataNodeUpdate(DataNode Updated) : NodeUpdate<DataNod
await test.RunAsync();
}

[Fact, WorkItem(7357, "https://github.com/dotnet/roslyn-analyzers/issues/7357")]
public async Task GenericDerivedType()
{
var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net70,
LanguageVersion = LanguageVersion.CSharp10,
TestCode = @"
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public static class Program
{
public static void Main()
{
// works as expected
new List<Base>() { new Derived() }.Cast<Derived>().ToList();

// same code but generic, fails
// CastTest\Program.cs(7,1,7,77): warning CA2021: Type 'GenericBase<int>' is incompatible with type 'GenericDerived' and cast attempts will throw InvalidCastException at runtime (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2021)
new List<GenericBase<int>>() { new GenericDerived() }.Cast<GenericDerived>().ToList();
}
}

class Base
{
}

class Derived : Base
{
}

class GenericBase<T>
{
}

class GenericDerived : GenericBase<int>
{
}"
};
await test.RunAsync();
}

[Fact]
public async Task NonGenericCasesVB()
{
Expand Down
Loading