5
votes

I have a C# class that has far too much code in, and I want to refactor it. What I would like to do is start with all the public methods, and build a tree for each one, showing which other methods in the class are called from it, and then which are called from the child one, and so on.

This will enable me to see which private methods belong solely to one public method, which are shared and so on.

Note that I DON'T want to do this at run time, I want to be able to look at a class, either directly at the .cs file, or using reflection on the compiled DLL.

I know I can use reflection on the compiled DLL to get the methods, but I can't find any way of finding out which methods are called by other methods in the class.

Anyone any ideas? Again, this is NOT a run time issue, it's purely to build a reusable utility to help refactor an oversized class. There are quite a few in the solution I'm working on, so the code woudl be used over and over again.

1
Resharper has this. It wills show you all usages of a method.Oded
Right-click on the method -> "View Call Hierarchy"?Brendan Hannemann
Of if you want to roll your own: stackoverflow.com/a/5741770/16959 this is an extremely well researched answer on this topicJason Sperske
Oded and unicron - Thanks for the replies, but I already know about the call hierarchy. However, unless I've missed something, they only allow you to see methods called by the current method. You then need to go through each called method and do the same thing on each of them. You also need to keep a track of all of this as you go along. This becomes very painful and error-prone very quickly. I'm looking for a way of generating a full hierarchy automatically. If either R# or VS's feature can do this, then please tell me how, as I didn't think they could.Avrohom Yisroel
Jason - thanks for the link, that looks fantastic. I haven't tried it yet, as it looks like it will need some serious study, but if it is as good as it looks, it should do exactly what I want. Thanks again.Avrohom Yisroel

1 Answers

10
votes

Visual Studio 2010 has action "View Call Hierarchy" where you can see all places in your solution where your code is invoked.

From my experience this static analysis may be somewhat lacking, for example method could be called dynamically using Reflection, through Data Binding, through Dependency Injection Container, etc.

Also, that may be bit off topic, and not applicable in your case, but I find a good way to find dead code for component is to have a suite of integration tests. Then you can run code coverage, and visually see what paths of code are never executed.