JetBrains Rider 2024.1 Help

Code inspection: Inline 'out' variable declaration

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.

void WriteValue(IDictionary<int, int> dictionary, int key) { int value; if (dictionary.TryGetValue(key, out value)) { Console.WriteLine(value); } }
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.

Last modified: 04 June 2024