JetBrains Rider 2018.2 Help

Introduce Variable refactoring

Refactor | Variable...
Ctrl+R, V

This refactoring allows you to create a new local variable or constant based on a selected expression, initialize it with the expression, and finally replace all occurrences of the expression in the method with references to the newly introduced variable.

In the example below, we use this refactoring to replace two occurrences of the same string with a variable:

Before refactoring

After refactoring

static void LogError(Exception ex) { Console.WriteLine("Something has failed..."); File.WriteAllText(@"c:\Error.txt", "Something has failed..." + ex); }

static void LogError(Exception ex) { var message = "Something has failed..."; Console.WriteLine(message); File.WriteAllText(@"c:\Error.txt", message + ex); }

To replace one or more occurrences of an expression with a variable

  1. Select an expression in the editor.

  2. Do one of the following:
    • Press Ctrl+R, V.

    • Press Ctrl+Shift+R and then choose Introduce Variable

    • Choose Refactor | Introduce Variable in the main menu.

  3. If more than one occurrence of the selected expression is found, JetBrains Rider displays the drop-down menu where you can choose whether to apply the refactoring to all occurrences or only to the current one.

  4. JetBrains Rider adds the new local variable and suggests to choose its type and name. You can choose one of the suggestions or type your own values. Press Tab or Enter to move to the next input position. Shift+Tab to return to the previous input position.

Last modified: 4 October 2018

See Also