Extract Method refactoring
This refactoring allows you to create a new method or a local function based on the selected code fragment. ReSharper analyses the selected statements and detects variables that can be converted into method parameters or represent its return value.
Consider the following example:
|Before refactoring||After refactoring|
| || |
To extract a method from a code block
- In the editor, select one or more statements that you want to convert into a method.
- Do one of the following:
- Press Ctrl+Alt+M.
- Press Ctrl+Shift+R and then choose Extract Method
- Right-click and choose Refactor | Extract Method in the context menu.
- Choose in the main menu.
- Choose how to extract the selected statements: as a method or as a local function:
- If you choose to create a local function, specify where to place the local function inside the current function.
- Click Next.
- Type a name for the new method in the Name field.
- Select one of expressions that ReSharper detected as possible method return values in the Return drop-down list. There may be other expressions detected as possible return values. They are listed as out parameters.
- Include or exclude parameters using 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, if necessary.
- To change order of parameters, select parameters in the list and use Move Up and Move Up buttons below the parameters list.
- If you choose to create a method, select the Make static and/or Make virtual to add the corresponding modifiers to the method.
- If you choose to create a method, you can also specify access rights in the Access rights drop-down list.
- Check the resulted method signature and body in the Preview field.
- To apply the refactoring, click Next.
- If no conflicts are found, ReSharper performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.
This feature is supported in the following languages and technologies:
The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see corresponding topics in the ReSharper by Language section. Specifically: