SA1503: Braces should not be omitted
Cause
The opening and closing braces for a C# statement have been omitted.
Rule description
A violation of this rule occurs when the opening and closing braces for a statement have been omitted. In C#, some types of statements may optionally include braces. Examples include if, while, and for statements. For example, an if-statement may be written without braces:
if (true)
return this.value;
Although this is legal in C#, StyleCop always requires the braces to be present, to increase the readability and maintainability of the code.
When the braces are omitted, it is possible to introduce an error in the code by inserting an additional statement beneath the if-statement. For example:
if (true)
this.value = 2;
return this.value;
Glancing at this code, it appears as if both the assignment statement and the return statement are children of the if-statement. In fact, this is not true. Only the assignment statement is a child of the if-statement, and the return statement will always execute regardless of the outcome of the if-statement.
StyleCop always requires the opening and closing braces to be present, to prevent these kinds of errors:
if (true)
{
this.value = 2;
return this.value;
}
C# 8 using declarations intentionally omit a braced block. Statements like using var stream = new MemoryStream(); (or await using for IAsyncDisposable) are valid and will not be flagged by this rule, because wrapping them in braces would alter the lifetime of the declared resource.
How to fix violations
The optional layoutRules.allowBracelessIfStatements setting defaults to "off". With "sameLine", a
standalone if may have a single-line jump statement without braces on the same line as its closing ).
With "nextLine", the jump must be on the immediately following line. This does not apply to any branch
of an if/else if/else chain, or to other statement bodies. Existing braced statements are unaffected.
The entire if header must fit on one line for either option; "sameLine" requires the whole if
statement to fit on one line. Multiline conditions require braces.
See Configuration.md for supported jumps and examples.
To fix a violation of this rule, wrap the body of the statement in braces.
How to suppress violations
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1503:BracesMustNotBeOmitted", Justification = "Reviewed.")]
#pragma warning disable SA1503 // BracesMustNotBeOmitted
#pragma warning restore SA1503 // BracesMustNotBeOmitted