Visual Studio Tip of the day – Refactoring – Extracting method

You notice that you have a chuck of code which could easily be transitioned to a new function. How tdo you do that?


Again, Visual Studio Refactoring menu comes to the rescue.


Suppose you have the following code in your function


public void Myfunc()


{


   Console.WriteLine(“a”);


   Console.WriteLine(“b”);


   Console.WriteLine(“c”);



   // Do some processing here.


   Console.WriteLine(“a”);


   Console.WriteLine(“b”);


   Console.WriteLine(“c”);


}


 


We realize that code containing Console.Writeline is replicated. Select one set of the Console.Writeline instructions and right click > Refactor > Extract Method…


Type the name of the new function you want to create containing the selected lines and Click OK.


A new method containing the selected lines is created. So your code will look like


public void Myfunc()


{


   NewMethod();



   // Do some processing here.


   Console.WriteLine(“a”);


   Console.WriteLine(“b”);


   Console.WriteLine(“c”);


}


private static void NewMethod()


{


   Console.WriteLine(“a”);


   Console.WriteLine(“b”);


   Console.WriteLine(“c”);


}


 


Keyboard shortcut: Ctrl R + Ctrl M


Cavaet: You will have to delete the second set manually as currently VS editor is not smart enough to replace all the occurances of the selected lines. Maybe in the next version we can get that feature.


 

3 Responses to “Visual Studio Tip of the day – Refactoring – Extracting method”

  1.   Kuzbass
    October 23rd, 2009 | 6:40 am       Reply

    homeowners insurance [url=”http://www.eliseogallery.com/Home-Insurance.html”]homeowners insurance[/url] http://www.eliseogallery.com/Home-Insurance.html 71120

  2.   onoffon
    January 11th, 2010 | 3:41 am       Reply

    cialis [url=”http://www.withcialis.com/”]cialis[/url] http://www.withcialis.com/ 84872

  3.   Slayer980
    January 25th, 2010 | 4:50 am       Reply

    phentermine [url=”http://www.phentermine-hcl.org/”]phentermine[/url] http://www.phentermine-hcl.org/ 75362

Leave a Reply