The Introduce Variable refactoring allows users to quickly create a new local variable or constant based on a selected expression, initialize it with the expression, and finally replace all the occurrences of the expression in the code with references to the newly introduced variable.
Introduce Variable is now implemented in dialogless mode, somewhat similar to live templates. That is, after you launch the refactoring upon a selection, ReSharper provides two drop-down lists for you to choose a type (anonymous/named) and a name (a couple of type-dependent options are suggested) for the new variable.
- Select an expression in the editor.
- Do one of the following:
- Choose ReSharper | Refactor | Introduce Variable on the main menu.
- Press Ctrl+Alt+V.
- Press Ctrl+Shift+R and select Introduce Variable in the Refactor This context menu:
- 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 will introduce a new variable and modify all referencing code accordingly.
The table below provides an example of using the Introduce Variable refactoring.
| Before: |
if(label.Text.Length>0)
{
if(label.Text.Contains(string)
{
...
}
...
}
|
| After: |
string text = label.Text;
if(text.Length>0)
{
if(text.Contains(string)
{
...
}
...
}
|
