Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect dead code in C#

How can I detect dead code in my C# application?

like image 406
santosh singh Avatar asked Dec 03 '10 18:12

santosh singh


People also ask

How do I find my dead code?

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.

Which testing can discover dead code?

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.

How do I get the dead code in C++?

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.

What is the difference between dead code and unreachable code?

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.


2 Answers

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.

like image 159
Justin Niessner Avatar answered Oct 23 '22 07:10

Justin Niessner


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.

like image 37
James Kovacs Avatar answered Oct 23 '22 06:10

James Kovacs