BRO1139: Write 'else if' on one line¶
An if that follows else on the next line, or that is the only statement of the else's block, is written as
else if. Not a StyleCop rule (Roslynator RCS0041, RCS1006).
Example¶
Before¶
public class Grades
{
public string Name(int score)
{
if (score >= 90)
{
return "A";
}
else
{
if (score >= 75)
{
return "B";
}
else
{
return "C";
}
}
}
}
After¶
public class Grades
{
public string Name(int score)
{
if (score >= 90)
{
return "A";
}
else if (score >= 75)
{
return "B";
}
else
{
return "C";
}
}
}
Why¶
An else that only holds another if is the next branch of the same decision. Written as else if, the branches line
up and the code doesn't drift right with each one.
How the fix works¶
The gap between else and if becomes one space, the block's } goes, and the if's other lines move left by as much
as the if moved (relative to the else's line). Where the whitespace formatting had left the if's body at the
if's column, each line goes where the joined chain wants it instead: its else lines and braces to the else if's
column, the rest one level deeper. Nested ones are fixed together, so one run is enough.
When the joined chain mixes clauses with and without braces, which ones BRO1514 and
BRO1516 report changes; the fix then adds the braces they want too, so the rules converge in one
dotnet format run in any order.
Not reported¶
- A comment or directive between
elseandif, or between the inner statement and the block's braces. - A block followed by another
else(if (a) if (b) X(); else { if (c) Y(); } else Z();): without the block, thatelsewould belong to the innerif. - An
ifwhose lines can't move left (not indented far enough), or that contains a token spanning several lines (a multi-line string) when its lines would move. - A block with other statements next to the
if.
Compared with StyleCop¶
StyleCop has no such rule. stylebro-migrate turns it off (see
Rules beyond StyleCop).