Skip to content

Commit

Permalink
fix false positive casting from value type constraint to Enum or Valu…
Browse files Browse the repository at this point in the history
…eType

dotnet#7031
  • Loading branch information
James May committed Feb 14, 2025
1 parent 8fe7aeb commit 9570f1d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,8 @@ static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbo
if (castToTypeParam.HasValueTypeConstraint
&& castFrom.TypeKind == TypeKind.Class)
{
return true;
return castFrom.SpecialType is not SpecialType.System_Enum
and not SpecialType.System_ValueType;
}

return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,35 @@ class GenericDerived : GenericBase<int>
await test.RunAsync();
}

[Fact, WorkItem(7031, "https://github.com/dotnet/roslyn-analyzers/issues/7031")]
public async Task GenericValueType()
{
// ensure runtime behavior is matches
_ = new Enum[] { StringComparison.OrdinalIgnoreCase }.Cast<StringComparison>().ToArray();
_ = new ValueType[] { int.MaxValue }.Cast<int>().ToArray();

var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
LanguageVersion = LanguageVersion.Latest,

TestCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
{
public static IEnumerable<T> CastEnums<T>(IEnumerable<Enum> values) where T : struct, Enum
=> values.Cast<T>(); // CA2021
public static IEnumerable<T> CastValueTypes<T>(IEnumerable<ValueType> values) where T : struct
=> values.Cast<T>(); // CA2021
}"
};
await test.RunAsync();
}

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

0 comments on commit 9570f1d

Please sign in to comment.