Link

Inline Variable Declaration

Microsoft Docs / out Variables

Recommendation

out variables should be declared inline when possible.

Use:

dictionaryWithEntry.TryGetValue(1, out string entry);

Not:

string entry;

dictionaryWithEntry.TryGetValue(1, out entry);

Justification

Both the Roslyn and .Net Core runtime teams agree that this language feature should be used.

Arguments

✔ Variable declaration occurs closer to where it will be used.

✔ No need to assign an initial value.

✔ By declaring the out variable where it’s used in a method call you can’t accidentally use it before it is assigned.

✔ Typically eliminates one line of code used to declare the variable elsewhere, and one blank line.

Performance

The same IL is generated regardless of if the out variable is declared inline or not.

Method Mean Error StdDev
NoOutVariableNonEmptyDictionary 6.383 ns 0.1909 ns 0.1785 ns
NoOutVariableEmptyDictionary 2.918 ns 0.1185 ns 0.1108 ns
OutVariableNonEmptyDictionary 6.308 ns 0.0890 ns 0.0789 ns
OutVariableEmptyDictionary 2.932 ns 0.0843 ns 0.0747 ns

Benchmark code

Benchmark IL

Exceptions

Analyzers

ID Name Value
IDE0018 csharp_style_inlined_variable_declaration true:suggestion

Discussion

GitHub Discussion