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 for casting interfaces from/to structs #6528

Merged
merged 1 commit into from
Mar 12, 2023
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 @@ -272,6 +272,11 @@ static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbo
case (TypeKind.Class, TypeKind.Interface):
return castFrom.IsSealed && !castFrom.AllInterfaces.Contains(castTo);

case (TypeKind.Interface, TypeKind.Struct):
return !castTo.AllInterfaces.Contains(castFrom);
case (TypeKind.Struct, TypeKind.Interface):
return !castFrom.AllInterfaces.Contains(castTo);

case (TypeKind.Class, TypeKind.Enum):
return castFrom.OriginalDefinition.SpecialType is not SpecialType.System_Enum
and not SpecialType.System_ValueType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,30 @@ public class DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzerTests
private readonly DiagnosticDescriptor castRule = DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.CastRule;
private readonly DiagnosticDescriptor ofTypeRule = DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.OfTypeRule;

[Fact]
public async Task CanCastRoundtripStructToInterface()
{
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;
var to = e.Cast<IInterface>();
_ = to.Cast<Implementation>();
}
}
");
}

[Fact]
public async Task OnlyWellKnownIEnumerable()
{
Expand Down