ReSharper Help  

Introduce Variable

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.

To introduce a variable

  1. Select the expression in the editor, and then do one of the following:
  2. 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.
  3. The Introduce Variable dialog box opens.

  4. In the Variable type list, select the type of the new variable. Note that you can see not only the type of the selected expression, but also all the types that it inherits and that are valid in this context.
  5. In the Variable name text box, type the variable name.
  6. If there are several expression usages in code, the Replace all occurences of expression check box becomes available. Select the check box if you want to replace the expression usages with the new variable.
  7. If the selected expression is a constant value, the Introduce constant check box becomes available. Select it if you want to introduce a contstant instead of the variable.
  8. Click Continue.

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

See Also

Refactoring Code