Refactoring Code using Visual Studio Extract Method

Visual Studio being an intelligent IDE does gives us a number of features that enhance the development of application as well as enhancing the way of coding continuously. One of such feature that has been added to VisualStudio IDE is refactoring. In this post we will see how easily we can use Refactoring feature of Visual Studio to get things done easily.

Visual Studio IDE ships with a new menu for refactoring code. Refactoring is actually a technique to change the software system in such a way so that the internal structure of the design changes and made more intuitive while the external behavior of the system remains same.

Lets take a look how the options works. In this post we are going to cover the Repeating code behaviour:

1. Refactoring a repeating code into a member:

Let us suppose we are going to refactor a code that looks like :

string arg1 = Console.ReadLine();
string arg2 = Console.ReadLine();

Console.WriteLine("You entered {0}", arg1);
Console.WriteLine("You entered {0}", arg2);

Now here the Console.WriteLine is repeating code. Now lets select the line and right click the repeating code and select Extract method. You can also press Ctrl + RM to invoke the Extract method. Let me select some portion of the code and use “Extract Method.. “. A dialog will appear which lets you rename the method extracted from the code.

The code will now look like :

static void Main(string[] args)
{
string arg1 = Console.ReadLine();
string arg2 = Console.ReadLine();

PrintMethod(arg1);
PrintMethod(arg2);
}

private static void PrintMethod(string arg1)
{
Console.WriteLine("You entered {0}", arg1);
}

Here the method is well extracted outside the body of the Main.

If you try with code that have external variables, you can see the Refactoring automatically detects it and produce the appropriate method stub. Refactoring does manual code analysis and is smart enough to detect the pros and cons of the refactored code and produce best alternative approach for you.

You should always use this menu to refactor your repeating code.

Tomorrow we will see how other menu in Refactor works. Stay tune.

Happy programming.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Refactoring Code using Visual Studio Extract Method”

Comments are closed.