Skip to content

Commit

Permalink
Fix CA2021 for casting interfaces from/to structs (#6528)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoyosjs authored Mar 12, 2023
1 parent 253bcd3 commit 5212c6e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
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

0 comments on commit 5212c6e

Please sign in to comment.