Skip to main content

Use NameOf

  • 2 minutes to read

Purpose

Converts a string literal to the nameof expression with the corresponding variable/member as an argument. The string literal should contain a variable or class member name.

You can use this refactoring instead of rename tools to keep your code valid when you rename definitions. This refactoring is better than the rename tools since these tools do not search for variable/member names within string literals.

Availability

Available when the caret is in a string literal that contains a variable/member name.

Usage

  1. Place the caret in a string literal that contains 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. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.

  3. Select Use NameOf from the menu.

    use-name-of-menu

After execution, this 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