The Introduce Variable 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 code with references to the newly introduced variable.
The refactoring is performed in dialogless mode. After you launch the refactoring on a selection, ReSharper provides two drop-down lists for you to choose a type and a name for the new variable.
- Select an expression in the editor.
Do one of the following:
- On the main menu, choose ReSharper | Refactor | Introduce Variable.
- Choose Refactor | Introduce Variable on the context menu.
- Press Ctrl+Shift+RCtrl+Shift+R, and then click Introduce Variable on the Refactor This menu.
- Press Ctrl+Alt+VCtrl+R,V.
- If your selected expression occurs multiple times in the local context, choose whether ReSharper should apply the refactoring to a single occurrence, or to all occurrences. If the selected expression occurs only once, proceed to the next step.
- In the drop-down list that displays, choose whether the new variable should be implicitly or explicitly typed.
- Press Tab to display another drop-down list that suggests names for the new variable. Choose a suggestion or type another name.
- Press Tab once again. ReSharper creates a new variable and modifies all occurrences of the expression accordingly.
Consider the example below:
After applying the refactoring, the occurrences of the expression are replaced with the data local variable.
This feature is supported in the following languages/technologies:
The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see the corresponding topics in the ReSharper by Language section.