Visual Studio: Create method from selected code lines (refactoring/redesign)

Those who program with Visual Studio (VS) sometimes find themselves in the situation where they want to outsource some lines of code within a method to a separate function/method. This may be because you want to make the code clearer or because the code in question is needed several times, and it therefore makes sense to create a separate method for the code.

The procedure for transferring existing code into a new method is called Refactoring (Restructuring/Redesigning Code). So you have to look for a corresponding entry in Visual Studio.

Refactoring with right-click does not work

The intuitive approach would be to select the lines of code in question and then right-click to find a corresponding entry for refactoring in the context menu. Unfortunately, one does not find the corresponding feature here.

Refactor via menu

Microsoft has placed refactoring in VS in the “Edit” menu or in the “Edit” menu in the German language setting. First select the desired code to be extracted and then use the menu to select “Refactor” ➥  “Extract Method…“.

Convert Visual Studio code selection to method
Select lines of code and choose from “Edit“, “Refactor“, “Extract method…

It will then replace the highlighted lines of code already with “NewMethod“, which will be inserted directly below as the new implementation of the method. At the same time, a small window opens in which you can adjust the name of the new method. In the example here, the name was changed to “UpdateProperties“. If you then press Enter, both the implementation and the inserted reference are automatically renamed. If you are unsure whether everything is working correctly, you can display a preview with the key combination “Shift+Enter“.

Screenshot Visual Studio assign new name for extracted method
enter new name for extracted method

In the following screenshot, you can see that a new method has been successfully created from the selected code. You can now reuse this method as often as you like.

Screenshot of the implementation of the new method and replacement of the selected code
Implementation of new method is inserted below and selected code lines are replaced with method

Key combination to extract a method

If the way via the Edit menu is too cumbersome for you, you can also reach your goal faster by using the appropriate key combination (shortcut). To do this simply:

    1. Select the code in question
    2. Press Ctrl+R and Ctrl+M one after the other (Ctrl key remains pressed)
    3. Assign method name and press Enter again.

Leave a Reply

Your email address will not be published. Required fields are marked *