Skip to content

Commit

Permalink
Fix a newly introduced FN
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim-Pohlmann committed Feb 13, 2023
1 parent 65a85b8 commit 92bd87d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
3 changes: 2 additions & 1 deletion analyzers/src/SonarAnalyzer.CSharp/Rules/RedundantCast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ private static void CheckCastExpression(SonarSyntaxNodeReportingContext context,

if (expression.Parent.Parent is AnonymousObjectMemberDeclaratorSyntax { Parent: AnonymousObjectCreationExpressionSyntax anon })
{
if (anon.Parent.Parent is ImplicitArrayCreationExpressionSyntax)
if (anon.Parent.Parent is ImplicitArrayCreationExpressionSyntax arrayCreation
&& arrayCreation.Initializer.Expressions.Skip(1).Any())
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ namespace Tests.Diagnostics
// https://github.com/SonarSource/sonar-dotnet/issues/3273
public class CastOnNullable
{
public void Simple()
{
var s1 = (string?)"Test"; // Noncompliant
var s2 = (string)s1!; // Noncompliant
}

public static IEnumerable<string> UsefulCast()
{
var nullableStrings = new string?[] { "one", "two", null, "three" };
Expand All @@ -25,6 +31,7 @@ public void Simple()
public void Array()
{
var anonArray = new[] { new { X = (string?)"foo" }, new { X = (string?)null } }; // Compliant
var oneElementAnonArray = new[] { new { X = (string?)"foo" } }; // Noncompliant
var notSoAnonArray = new[] { new HoldsObject(new { X = (string?)"foo" }) }; // Noncompliant
}

Expand Down

0 comments on commit 92bd87d

Please sign in to comment.