Skip to main content
A newer version of this page is available. .

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

  1. 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.

    public void AddRecord(object data1, object data2, object data3) {
        if (data1 == null)
            throw new ArgumentNullException("data1");
        //...
    }
    
  2. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
  3. 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.

See Also