I have a C# project for which I need to find the all private methods which are not called from any other public method directly or indirectly.
In addition, for each private method which is called from a public method, I need to know which public method it is. Then I will detemine if that method is really called from a client of the class and if not I will be able to remove it.
In the past I used a code from Lutz Rorder which is the base of Reflector - it had an option to analyze IL code and gave object model on top of it. I cannot find this code now.
Any suggestion? Maybe a point to that Lutz Rorder code?
Saar
You should check out Nitriq Static Code Analysis for .Net - They have a free community edition and their full blown license is pretty reasonable.
As pointed Thomas the tool NDepend can help you to find unused code in a .NET code base. Disclaimer: I am one of the developer of this tool.
NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection:
NDepend is integrated in Visual Studio, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
In addition, for each private method which is called from a public method, I need to know which public method it is.
To obtain this information, with CQLinq you just need to write:
from m in Application.Methods
where m.IsPrivate
let publicMethodsCallingMe = m.MethodsCallingMe.Where(m1 => m1.IsPublic)
where publicMethodsCallingMe.Count() > 0
select new { m, publicMethodsCallingMe }
The query result will be easily browsable:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With