9

I want to move a class form one namespace to another, programmatically. This includes adjusting any dependencies the moved class had in its previous namespace.

I'm guessing that I can make use of the Roslyn project somehow, but I can't finding a starting point.

Edit:

I'm trying to implement an automatic move class refactoring on C# code. Doing it for study purposes - gathering code metrics and studying the changes before and after the refactoring process.

I can do the refactorings by hand, but was wondering If I can do it automatically. This means that I already have the refactoring candidates and their proposed move locations.

Teodor Kurtev
  • 1,049
  • 1
  • 13
  • 24
  • This sounds like the [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why are you trying to do this? – Yuval Itzchakov Jan 31 '17 at 09:42
  • I've put an explanation in the main question. – Teodor Kurtev Jan 31 '17 at 09:53
  • Related: [Fastest way to update namespaces with ReSharper](http://stackoverflow.com/questions/791253/fastest-way-to-update-namespaces-with-resharper). This might be helpful to users **not** interested in creating their own implementation – in contrast to OP. – Søren D. Ptæus Jan 31 '17 at 10:22

1 Answers1

10

There is no built-in support for this, so yes, you'd have to implement this yourself.

If you did want to try this, there's some high level steps you'd probably do:

  1. You'd first call SymbolFinder.FindReferences to figure out where your type name is being mentioned.
  2. For each document you find a reference to, use a SyntaxRewriter to rewrite the syntax.
  3. Put the new syntax there.
  4. Run our simplifier process to get everything cleaned back up.

You could dig through our rename code to see how we do this, but I'll warn you it's fairly complex. This refactoring is probably "medium" in terms of difficulty, so not to dissuade you but you have an uphill battle if you tried this as your first introduction to Roslyn.

(Motto: refactorings are always harder than you think they are.)

Jason Malinowski
  • 18,148
  • 1
  • 38
  • 55