Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull a method out of its class (and into a new or existing)?

What is the easiest way of pulling an existing method out of its class and into a new class using Visual studio 2010 / Resharper?

Edit: I use Resharper version 5.

like image 250
Slampen Avatar asked May 03 '10 05:05

Slampen


People also ask

How do you move a method to another class in Python?

If you go to each method and right-click on its name, the menu has a "Refactor" option, which leads to a "Move" option.

How do I move a method from one class to another in eclipse?

To move this method to the new class, highlight the method's name and select Refactor→ Move, or right-click and select Refactor→ Move, opening the Move Static Member(s) dialog shown in Figure 4-5. In Eclipse, you can move a static method, static field, or instance method using refactoring.


3 Answers

Starting with

public void Method() {}

  1. First, make the method static using the "Make Method Static" command.

    public static void Method(){}

  2. Then, add a local variable of the type of the new class:

    public static void Method(){Class2 me = new Class2();}

  3. Then, use Introduce Parameter

    public static void Method(Class2 me) {}

  4. Then use "Make Method non-Static". In class2:

    public void Method(){}

like image 110
John Saunders Avatar answered Oct 21 '22 01:10

John Saunders


Same as above, but I would not do the conversion to static-method manually. Pull up the "Refactor this" menu (using shortcuts of course, ctrl+shift+R), then select "Make method static", then "Refactor this"->"Move".

Note:

If you're talking about moving a method in a class hierarchy, you can use "Push members down" or "Pull members up"

like image 37
Marius Avatar answered Oct 21 '22 00:10

Marius


In up-to-date Resharper, there's Move Refactoring. You either press F6 while the cursor is in method signature, or cut-paste code to the new location, and Resharper offers you to apply the refactoring.

like image 29
Vladimir Smirnov Avatar answered Oct 21 '22 01:10

Vladimir Smirnov