Tips & Tricks: Extract Method in Visual Studio

Introduction:

Extract Method is a feature in Visual Studio, which will be used to refactor the code. Here refactor means moving specific functionality into seperate method.

Example:

Suppose i have a code as shown below:

class Program
{
    static void Main(string[] args)
    {
        int year = DateTime.Now.Year;
        Console.WriteLine(string.Format("Current Year: {0}", year));
    }
}

Here it will prints the current year. Suppose if there is a requirement like, needs to print current year in other parts of the project.

What we will do?

A normal developer will writes the same code wherever the functionality required. To reuse the same functionality in other parts of the project, we will create a method with some name and we will cut/paste this code into new method. Then new method will be called wherever required. See the below code:

class Program
{
    static void Main(string[] args)
    {
        DisplayCurrentYear();
    }

    private static void DisplayCurrentYear()
    {
        int year = DateTime.Now.Year;
        Console.WriteLine(string.Format("Current Year: {0}", year));
    }
}

In the above, we are doing some manual work like: creating new method, cut & paste the existing code into new method, and calling the new method.

How to reduce manual work?

To reduce the manual work goto intial code and select the lines of code which you want to move as shown below:

Right click on it, you will see the Refactor and other options as shown below:

If you goto Refactor, you will find suboptions like Rename, Extract Method,...

Select Extract Method option as shown below:

Then it will asks for New method name in a popup window as shown below:

Enter new method name and then press OK. Now you will  see the final code as shown below:

Thats it. I hope you enjoyed this article. We will add more articles on "Tips & Tricks" in the coming days.

  • Created
    Apr 03, 2015
  • Updated
    Apr 03, 2015
  • Views
    275