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 S3431 FN: Multiline statement should not be count as one line statement #9618

Open
sebastien-marichal opened this issue Aug 8, 2024 · 0 comments
Labels
Area: C# C# rules related issues. Type: False Negative Rule is NOT triggered when it should be.

Comments

@sebastien-marichal
Copy link
Contributor

S3431 has an exception for single-line tests.
To check this, we count the number of statements in the method body

protected override bool HasMultiLineBody(SyntaxNode syntax)
{
var declaration = (MethodDeclarationSyntax)syntax;
return declaration.ExpressionBody is null
&& declaration.Body?.Statements.Count > 1;
}

However, this will be count has one:

[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void TestMethod()
{
    try // This is one statement
    {
        Console.ForegroundColor = ConsoleColor.Black;
        using var _ = new ConsoleAlert();
        Assert.AreEqual(ConsoleColor.Red, Console.ForegroundColor);
        throw new InvalidOperationException();
    }
    finally
    {
        Assert.AreEqual(ConsoleColor.Black, Console.ForegroundColor);
    }
}

public sealed class ConsoleAlert : IDisposable
{
    private readonly ConsoleColor previous;

    public  ConsoleAlert()
    {
        previous = Console.ForegroundColor;
        Console.ForegroundColor = ConsoleColor.Red;
    }
    
    public void Dispose() =>
        Console.ForegroundColor = previous;
}

The method body has only one statement which is the try statement, discarding the lines within the try statement.
This applies to some other statements as well (non-exhaustive):

  • Block
  • CatchClause
  • CheckedStatement
  • DoStatement
  • FinallyClause
  • FixedStatement
  • ForEachStatement
  • ForEachVariableStatement
  • ForStatement
  • IfStatement
  • LockStatement
  • SwitchStatement
  • TryStatement
  • UncheckedStatement
  • UnsafeStatement
  • UsingStatement
  • WhileStatement

This does not seem to be an issue in VB.NET, might need more investigation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: C# C# rules related issues. Type: False Negative Rule is NOT triggered when it should be.
Projects
None yet
Development

No branches or pull requests

1 participant