BRO1132: Block statements should not contain embedded comments¶
A comment between a statement's header and the { of its block moves into the block. Replaces StyleCop SA1108.
Example¶
Before¶
public class Cache
{
private object items;
public object Get()
{
if (items == null) // first use
{
items = new object();
}
else // already loaded
{
return items;
}
return items;
}
}
After¶
public class Cache
{
private object items;
public object Get()
{
if (items == null)
{
// first use
items = new object();
}
else
{
// already loaded
return items;
}
return items;
}
}
Why¶
A comment squeezed between if (...) and { is easy to miss and sits apart from both the condition and the code it
explains. On its own line at the top of the block it reads as what it usually is: a note about the branch.
How the fix works¶
Each comment goes on its own line right after { (below blank lines there, which are BRO1503's),
indented like the block's first line (one level deeper than { in an empty block), in its original order and above any
comment already there. The rest of the header's line stays as it was; a line that held only the comment is removed.
Checked like StyleCop: the blocks of if, else, for, foreach, while, do, lock, try, catch, finally,
checked, unchecked and fixed, and a switch statement's braces. Both // and /* */ comments count, after the
header on its line or on a line of their own before {.
A comment that another tool reads by its line, such as a suppression (catch (X) when (...) // slopwatch-ignore: SW003),
moves too, like any other: StyleCop reports it the same way, so StyleBro does as well (the owner's
decision).
Where that tool needs the comment on the header's line, turn BRO1132 off (dotnet_diagnostic.BRO1132.severity = none)
or accept the move and suppress the finding the tool's own way.
Not reported¶
////comments (commented-out code), like StyleCop.- A comment after
{({ // note), inside the condition, or above the statement. - Other blocks:
using, a deconstructingforeach (var (a, b) in ...), lambda bodies, plain blocks (StyleCop doesn't check them). Types, namespaces, members, accessors and local functions are BRO1134's. - A header spanning several lines (from the keyword to the token before
{): in a condition split over lines, the comment at its end usually explains the last line, often as one of a column of comments, and would read as a note about the body once moved. Each clause counts on its own:else // cafter a multi-lineifis reported. - A single-line block (
if (x) // note+{ y(); }): there's no line inside it for the comment. - A comment spanning lines or a directive between the header and
{.
Compared with StyleCop¶
StyleCop has no fix. Same positions, except the skipped cases above (the multi-line header skip was the owner's decision, see docs/decisions.md).