JetBrains Rider 2022.2 Help

Code Inspection: Use 'nameof' expression to reference name

In .NET 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, JetBrains Rider 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.

public void OrderErrorHandler(object order) { if (order == null) throw new ArgumentNullException("order"); /* ... */ }
public void OrderErrorHandler(object order) { if (order == null) throw new ArgumentNullException(nameof(order)); /* ... */ }
Last modified: 08 March 2021