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…“.
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“.
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.
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:
- Select the code in question
- Press Ctrl+R and Ctrl+M one after the other (Ctrl key remains pressed)
- Assign method name and press Enter again.