How can I detect dead code in my C# application?
The quickest way to find dead code is to use a good IDE. Delete unused code and unneeded files. In the case of an unnecessary class, Inline Class or Collapse Hierarchy can be applied if a subclass or superclass is used. To remove unneeded parameters, use Remove Parameter.
Polyspace tools help you identify dead or unreachable code in your software. This saves time and reduces the cost associated with testing activities geared for robustness and complete code coverage.
One approach is to use "Find All References" context menu item on class and function names. If a class/function is only referenced in itself, it is almost certainly dead code. Another approach, based on the same idea, is to remove(comment out) files/functions from project and see what error messages you will get.
MISRA C defines unreachable code as code that cannot be executed, and it defines dead code as code that can be executed but has no effect on the functional behavior of the program.
ReSharper can handle that. You could also check out NDepend.
If you don't feel like paying for either of those, I believe you can analyze your project with FxCop and it will also identify dead code.
Compile your code and check the warnings in the Error List. The following code:
public ActionResult Index() {
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
return null; // unreachable
}
produces this warning:
Warning 11 Unreachable code detected <fullpath>\HomeController.cs 13 13 <prjname>
Tools like JetBrains ReSharper (http://jetbrains.com/resharper)* can also perform this analysis on the fly and highlight dead code.
* ReSharper is a commercial tool.
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