Is it possible to move a static method into another class and refactor simultaneously on Visual Studio? C#

Viewed 1111

Pardon if this has been answered somewhere before.

I am not entirely sure how to phrase this question, so I'll do an example:

Lets say we have 2 different classes, A and B. If I have a static method in class A that I normally call by using "A.Method()" in my program, would it be possible to move this method from A to B so that it automatically refactors this new location "B.Method()" everywhere in the program?

In short, I would like to refactor the "location", rather than the method's "name", as I am moving methods from many different classes into one static method library.

Thank you for any pointers you can provide.

3 Answers

Not directly, but if you're sneaky, you can do it this way.

  1. Change the name of B to C. Do not auto-refactor. This will break compilation temporarily.
  2. Change the name of A to B. This time, do allow the auto-refactor. This will change all instances of A.Method() to calls to B.Method().
  3. Move (copy and paste) the code from C back into B. This will fix the compilation errors introduced in step 1.

On the other hand, it might be simpler just to use a traditional search and replace (ctrl+F or shift+ctrl+F).

One of the approaches that you could consider is to rename the namespace of class A to be class B. Find out what files broke from the change, then do find and replace and this files to switch the using namespace to the one that class B reside.

The refactoring tool like ReSharper might be able to shorten the amount of work.

I am currently moving public static User activeUser = null; from the class Interface to the class BankManager. And this is how I do it:

  1. CTRL-F for opening the search function. You get the following window in the top right(At least I do):

enter image description here

  1. Then press the down arrow:

enter image description here

  1. Then press the other down arrow:

enter image description here

  1. And now select the option "Entire Solution".

enter image description here

  1. In the "Search" box, I write what is currently used to reference activeUser from other classes, namely Interface.activeUser.

enter image description here

  1. Then in the "Replace" box, I write what will be used.

enter image description here

  1. Then finally, I hit the "replace all" icon.

enter image description here

  1. And now, every other instance of Interface.activeUser in the entire solution has changed.

  2. If you also referenced the activeUser within the Interface class, you'll likely need to do the same but instead you'd do:

enter image description here

After this, at least in my experience it's all done. And sure, there's a lot of little steps. I simply wanted to be very thorough in my explanation. But it only takes about 20-30 seconds at most.

Hope it helps someone!

Related