The Introduce Variable refactoring allows users to quickly create a new local variable or constant from the 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.
You can see usage examples of the Introduce Variable refactoring in the table below.| Before | After |
|---|---|
if(label.Text.Length>0)
{
if(label.Text.Contains(string)
{
...
}
...
}
|
string text = label.Text;
if(text.Length>0)
{
if(text.Contains(string))
{
...
}
...
}
|
ArrayList list = new ArrayList();
...
list.Add("Item: " + first);
list.Add("Item: " + second);
|
ArrayList list = new ArrayList(); ... const string s = "Item: "; list.Add(s + first); list.Add(s + second); |
Tip Try to create a new variable by typing the expression and pressing Ctrl + Alt + V. It is much faster than to type the variable declaration yourself.
Tip You may find using the Ctrl + W (extend selection) shortcut to be a great tool for selecting expressions before applying the Introduce Variable refactoring.
The Introduce Variable dialog box opens.

If no conflicts are found, the changes are applied immediately.