ReSharper Help  

Introduce Field

The Introduce Field refactoring allows users to quickly create a new field 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 field.

You can see a usage example of the Introduce Field refactoring in the table below.
Before After
public class DemoForm:Form
{
   private Panel myPanel;
   
   public DemoForm()
   {
      myPanel.Controls.Add(new Button());
      ...
   }
}
public class DemoForm:Form
{
   private Panel myPanel;
   private Button myButton;
   
   public DemoForm()
   {
      myButton = new Button();
      myPanel.Controls.Add(myButton);
      ...
   }
}
Tip    Try to create a new field by typing the expression and pressing Ctrl + Alt + D. It is much faster than to type the field declaration yourself.

To introduce a field

  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 Field refactoring.
  3. The Introduce Field dialog box opens.

  4. In the Type list, select the type of the new field. 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 Name text box, type the field name.
  6. In the Initialize in group, select where to initialize the field: in the class member where you selected the expression, in the field declaration, or in the class constructors.
  7. In the Visibility group, select the visibility of the new field.
  8. 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 field.
  9. If you want to create a read-only field, select the Declare readonly check box.
  10. If the selected expression is a constant value, the Introduce constant check box becomes available. Select it if you want to introduce a contstant field.
  11. Click Continue.

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

See Also

Refactoring Code