How can I detect dead code in my C# application?
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.
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.
Mind that these tools do not detect the dead code in the comments. For example, the following:
// var a = 123;
// DoSomething(a);
will not be detected as dead code.
As of July 2020, I could not find any code inspection tool that could detect dead code in the comments. Therefore I developed one on my own (based on Roslyn) and published it under MIT license: https://github.com/mristin/dead-csharp.
© 2022 - 2024 — McMap. All rights reserved.