Table of Contents

SA1500: Braces for multi-line statements should not share line

Cause

The opening or closing brace within a C# statement, element, or expression is not placed on its own line.

📝 The behavior of this rule can change based on the configuration of the allowDoWhileOnClosingBrace property in stylecop.json. See Configuration.md for more information.

Rule description

A violation of this rule occurs when the opening or closing brace within a statement, element, or expression is not placed on its own line. For example:

public object Method()
{
    lock (this) {
        return this.value;
    }
}

When StyleCop checks this code, a violation of this rule will occur because the opening brace of the lock statement is placed on the same line as the lock keyword, rather than being placed on its own line, as follows:

public object Method()
{
    lock (this) 
    {
        return this.value;
    }
}

A violation will also occur if the closing brace shares a line with other code. For example:

public object Method()
{
    lock (this) 
    {
        return this.value; }
}

Starting with C# 8.0, this rule also applies to braces introduced by switch expressions and property patterns. When the arms or pattern contents span multiple lines, the { and } must appear on their own lines. A multiline switch expression's closing brace must not share a line with the final arm, but may be followed on the same line by code continuing the expression, such as a null-coalescing operator (??).

Switch expressions entirely on one line are allowed. The spacing requirements of SA1012 and SA1013 still apply.

Starting with C# 12, this rule also applies to multiline collection expressions ([ ... ]). The opening [ may follow other code on the same line, such as an assignment, but the first element must start on a later line. The closing ] must start on its own line, even when the last element has a trailing comma. Code continuing the expression, such as ); or a comma, may follow the closing bracket on the same line. For example:

int[] values = [
    1,
    2,
];

Single-line collection expressions, including empty collections, are allowed. Bracket and element indentation is checked separately by SA1137.

How to fix violations

To fix a violation of this rule, ensure that both the opening and closing braces are placed on their own line, and do not share the line with any other code, other than comments.

For a collection expression whose opening bracket follows other code on its line, the code fix also offers an option to align the closing bracket with the opening bracket.

How to suppress violations

[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1500:BracesForMultiLineStatementsMustNotShareLine", Justification = "Reviewed.")]
#pragma warning disable SA1500 // BracesForMultiLineStatementsMustNotShareLine
#pragma warning restore SA1500 // BracesForMultiLineStatementsMustNotShareLine