diff --git a/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/StringFormatValidator.cs b/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/StringFormatValidator.cs index a127f65d050..35ff9272fc3 100644 --- a/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/StringFormatValidator.cs +++ b/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/StringFormatValidator.cs @@ -435,14 +435,15 @@ public static FormatStringArgument Create(ExpressionSyntax expression, SemanticM { var type = semanticModel.GetTypeInfo(expression).Type; var arraySize = -1; - if (type.Is(TypeKind.Array)) + if (type != null && type.Is(TypeKind.Array)) { if (expression is ImplicitArrayCreationExpressionSyntax implicitArray) { arraySize = implicitArray.Initializer.Expressions.Count; } - if (expression is ArrayCreationExpressionSyntax array) + if (expression is ArrayCreationExpressionSyntax array && + array.Initializer != null) { arraySize = array.Initializer.Expressions.Count; } diff --git a/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/Rules/StringFormatValidatorTest.cs b/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/Rules/StringFormatValidatorTest.cs index 20e15525f91..0fdab2795f4 100644 --- a/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/Rules/StringFormatValidatorTest.cs +++ b/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/Rules/StringFormatValidatorTest.cs @@ -58,5 +58,14 @@ public void StringFormatTypoFreeValidator() new StringFormatValidator(), workingOptions); } + + [TestMethod] + [TestCategory("Rule")] + public void StringFormatEdgeCasesValidator() + { + Verifier.VerifyAnalyzer(@"TestCases\StringFormatEdgeCasesValidator.cs", + new StringFormatValidator(), + workingOptions); + } } } diff --git a/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/TestCases/StringFormatEdgeCasesValidator.cs b/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/TestCases/StringFormatEdgeCasesValidator.cs new file mode 100644 index 00000000000..1ac2959cf70 --- /dev/null +++ b/sonaranalyzer-dotnet/tests/SonarAnalyzer.UnitTest/TestCases/StringFormatEdgeCasesValidator.cs @@ -0,0 +1,26 @@ +using System.Text; + +namespace Tests.Diagnostics +{ + public class StringFormatEdgeCasesValidator + { + // See https://github.com/SonarSource/sonar-dotnet/issues/2392 + void EdgeCases(string bar) + { + var builder = new StringBuilder(); + builder.AppendFormat("&invoice={0}", Foo(bar)); + builder.AppendFormat("&invoice={0}", new object[0]); + builder.AppendFormat("&invoice={0}", new object[1] { 1 }); + builder.AppendFormat("&invoice={0}", new [] { 1 }); + builder.AppendFormat("&rm=2", new object[0]); + builder.AppendFormat("&rm=2", new[] { 1 }); // Noncompliant + builder.AppendFormat("&rm=2", new object[0] { } ); // Noncompliant + builder.AppendFormat("&rm=2", new object[1] { "a" } ); // Noncompliant + } + + string Foo(string bar) + { + return ""; + } + } +}