Code inspection: Extract common code
Category: Potential Code Quality Issues
ID: ExtractCommonBranchingCode
EditorConfig: resharper_extract_common_branching_code_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
This inspection reports equivalent code in different branches of if
and switch
statements. The corresponding quick-fix helps you automatically extract the duplicated code and put it either before or after the branching.
If the equivalent code is intended, consolidating common statements makes your code cleaner and easier to maintain. However, this inspection can also be useful to catch bugs because often the equivalent code in branching constructs is the result of copy-pasting. So when you see this issue in your code, first check whether the equivalent code is intended.
Suboptimal code
void GreetCustomer(string name, bool known){ var sb = new StringBuilder(); if (known) { sb.AppendLine($"Hello, {name}!"); sb.AppendLine("Welcome back!"); } else { sb.AppendLine($"Hello, {name}!"); sb.AppendLine("Welcome!"); } Console.WriteLine(sb.ToString());}
After the quick-fix
void GreetCustomer(string name, bool known){ var sb = new StringBuilder(); sb.AppendLine($"Hello, {name}!"); if (known) { sb.AppendLine("Welcome back!"); } else { sb.AppendLine("Welcome!"); } Console.WriteLine(sb.ToString());}