Code Inspection: Use 'nameof' expression to reference name
In .NET standard libraries, there are a lot of methods that are designed to accept names of types, members, or variables as arguments. One of the most common examples is the
ArgumentNullException(string paramName). If you use string literals as the arguments for such methods, you can run into errors if the literal is misspelled or not changed when the corresponding symbol was renamed. A string literal that does not correspond to any valid symbol is not caught by the compiler.
The nameof operator, added in C# 6.0, addresses this — it allows capturing the string names of symbols that are in the scope.
In the example below, ReSharper suggests the replacement of the string literal
"order" in the argument of the
ArgumentNullException() with the
nameof(order). The result is the same:
nameof(order) returns the string 'order', but with
nameof your code becomes less error-prone.
|Suboptimal code||After the quick-fix|
| || |