Nested ‘if’ statements can be combined¶
ID: cs/nested-if-statementsKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - maintainability - readability - language-featuresQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
It is unnecessary to nestif statements when neither of them has anelse part. The code can be written more simply by combining the statements into a singleif statement.
Recommendation¶
Combine theif statements into a singleif statement. Combine the conditions using an&& operator.
Be sure to check operator precedence and use brackets around each condition where necessary.
Example¶
This example shows twoif statements which are nested.
if(connection.Status==Connected){if(!connection.Authenticated){connection.SendAuthRequest();}}
Since neither of the statements has anelse part, the code can be rewritten as follows:
if(connection.Status==Connected&&!connection.Authenticated){connection.SendAuthRequest();}
References¶
MSDN:if-else (C# Reference).
MSDN:C# Operators.