Use nameof
- 2 minutes to read
Purpose
Converts the string literal containing a variable or class member name to the nameof expression with the corresponding variable/member as an argument. Using nameof helps keep your code valid when renaming definitions, because the majority of automatic renaming tools do not search for variable/member names within string literals.
Availability
Available when the caret is on a string literal containing a variable/member name.
Usage
Place the caret on a string literal containing a variable or member name.
NOTE
The blinking cursor shows the caret's position at which the Refactoring is available.
- Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
- Select Use nameof from the menu.
After execution, the Refactoring changes the string literal to the nameof expression with the corresponding variable/member as an argument.
public void AddRecord(object data1, object data2, object data3) {
if (data1 == null)
throw new ArgumentNullException(nameof(data1));
//...
}
NOTE
This feature is available as a part of Code Cleanup.