ReSharper Web Help

The Extract Method refactoring allows you to create a new method based on a selected code fragment. ReSharper analyses the selected block of code and detects variables that can be converted into method parameters or represent its return value. This refactoring can be applied to any expression.

The reverse functionality is provided by the Inline Method refactoring.

To extract a method
  1. In the editor, select a block of code to be converted into a method.
  2. Do one of the following:
    • On the main menu, choose ReSharper | Refactor | Extract Method.
    • Right-click, then click Refactor | Extract Method on the context menu.
    • Press Ctrl+Shift+RCtrl+Shift+R, then click Extract Method.
  3. The Extract Method dialog box opens. Type a name for a new method in the Name text box.

    Refactorings__Extract_Method

  4. Select one of expressions that ReSharper detected as possible method return values in the Return drop-down list.

    Note

    Other expressions detected as possible return values are listed as parameters with the out modifier in the parameters list.
  5. Include or exclude parameters by selecting or clearing the corresponding check boxes in the Parameters area. If you exclude a parameter from the list, the local variable with the same name and type will be created in the method.
  6. Select the Make static check box to create a static method.
  7. Select the Make virtual check box to create a virtual method.
  8. Specify access rights in the Access rights drop-down list.
  9. Check the results in the Signature preview text area, and click Next. If no conflicts are found, ReSharper performs the refactoring immediately. Otherwise, resolve conflicts.

Warning

If the selected block of code has multiple exit points (for example, the block has a conditional return statement), the Extract Method refactoring can change the code semantics and/or produce non-compilable code.

Consider the following example:

public void Foo()
{
    ...
    if(i>0)
        return;
    i++;
    Console.WriteLine(i);
   ...
}

If you try to extract a method from the selected code block, ReSharper will show a warning notifying that the refactoring is not safe.


This feature is supported in the following languages/technologies:

C# VB.NET HTML ASPX Razor JavaScript TypeScript CSS XML XAML RESX Build Scripts
feature_available feature_available

Tip

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.