Refactoring is the process of improving your code after it has been written, by changing the internal structure of the code without affecting its functionality. Extract Method is a refactoring operation in Visual Studio 2010 that provides an easy way to create a new method from a code fragment, in an existing member.
In order to use Extract Method, you require to select a code fragment. Let us see an example:
Check this piece of code
In the code above, the process of checking the validity of the connection string should ideally be put in a new method. This is very simple using the Extract method refactoring. Just select the code fragment and right click > Refactor > Extract Method (or Ctrl + R, Ctrl + M) as shown below:
In the Extract Method dialog box, enter the new method name and hit OK
When you click OK, Visual Studio 2010 creates a new method and moves the selected
code fragment to the body of the new method, in our case AlternateConnectionString(). It also creates appropriate parameters and even returns a value, if needed, by the calling code.
The original code (where the code fragment was), is replaced with a call to the new method, with any applicable parameters that are to be passed to the new method or add a local variable to receive the return value.
The code fragment after refactoring looks like this:
Note: The Extract Method Refactor is smart! For eg: if your code does not access any instance-specific data, the Extract method refactoring makes the new method static.
Similarly, you can even extract a single line of code or a portion of a code, as its own method.
Will you give this article a +1 ? Thanks in advance