Code inspection: Inline 'out' variable declaration
Category: Language Usage Opportunities
ID: InlineOutVariableDeclaration
EditorConfig: resharper_inline_out_variable_declaration_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
This inspection suggests inlining the out
variable declaration to simplify your code and increase readability.
Starting with C# 7.0, as a part of enhancements to out
variables, you can declare out
variables in the argument list of a method, rather than writing a separate declaration statement.
Suboptimal code
void WriteValue(IDictionary<int, int> dictionary, int key){ int value; if (dictionary.TryGetValue(key, out value)) { Console.WriteLine(value); }}
After the quick-fix
void WriteValue(IDictionary<int, int> dictionary, int key){ if (dictionary.TryGetValue(key, out var value)) { Console.WriteLine(value); }}
As you can see, after the quick-fix the scope of value
is narrowed down to the if
statement, which follows the principle of limiting variable scope as much as possible. Furthermore, it helps you locate variable declarations more easily because they are typically closer to where the variables are first used in the code. Its availability in the preceding code lines is also removed, preventing potential misuse of the uninitialized variable.