← 返回首页
Nested ‘if’ statements can be combined — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

Nested ‘if’ statements can be combined

ID: cs/nested-if-statements Kind: problem Security severity: Severity: recommendation Precision: high Tags: - quality - maintainability - readability - language-features Query suites: - csharp-code-quality.qls - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

It is unnecessary to nest if statements when neither of them has an else part. The code can be written more simply by combining the statements into a single if statement.

Recommendation

Combine the if statements into a single if 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 two if statements which are nested.

if(connection.Status == Connected) { if(!connection.Authenticated) { connection.SendAuthRequest(); } }

Since neither of the statements has an else part, the code can be rewritten as follows:

if(connection.Status == Connected && !connection.Authenticated) { connection.SendAuthRequest(); }

References