BRO1137: Remove a redundant 'return;' or 'yield break;'¶
A return; as the last statement of a body, or a yield break; as the last statement of an iterator, does nothing:
the body ends there anyway. From Roslynator's RCS1134. bro migrate turns it off.
Example¶
Before¶
using System.Collections.Generic;
public class Log
{
private readonly List<string> lines = new List<string>();
public void Add(string line)
{
if (line.Length == 0)
{
return;
}
lines.Add(line);
return;
}
public IEnumerable<string> Errors()
{
foreach (var line in lines)
{
if (line.StartsWith("error"))
{
yield return line;
}
}
yield break;
}
}
After¶
using System.Collections.Generic;
public class Log
{
private readonly List<string> lines = new List<string>();
public void Add(string line)
{
if (line.Length == 0)
{
return;
}
lines.Add(line);
}
public IEnumerable<string> Errors()
{
foreach (var line in lines)
{
if (line.StartsWith("error"))
{
yield return line;
}
}
}
}
Why¶
A jump that goes where the code would go anyway makes the reader look for a reason that isn't there.
How the fix works¶
The statement's line is removed, with the blank lines above it (they would end up before the body's }, which
BRO1518 reports). A statement that shares its line with other code is removed with the spaces before it:
void M() { return; } becomes void M() { }.
Not reported¶
- A
return;oryield break;in a nested block (if (x) { ...; return; }): code after the block would run. - A
yield break;that is the iterator's onlyyield(it is what makes the method an iterator). - A statement with a comment on it or above it, or a label (
end: return;). - A directive right above the statement (
#endif,#if): which statement is last can depend on it. return x;(a value) and expression-bodied members.