Home
C#
Unreachable Code Detected
Updated Dec 22, 2023
Dot Net Perls
Unreachable code. This kind of code is never executed. The C# compiler issues an unreachable code detected warning. This warning can help you eliminate unused code.
Code notes. We look at unreachable code. We see how to eliminate this error but not remove the code—pragma directives can be used for this purpose.
This C# program has some unreachable code. In the while-loop, the condition must be evaluated before the loop body is entered. In a while false loop, all the enclosed code is unreachable.
while
And The compiler can figure this out before the program ever executes. It will generate an unreachable code detected warning.
using System; class Program { static void Main() { while (false) { int value = 1; if (value == 2) { throw new Exception(); } } } }
Warning CS0162: Unreachable code detected
Example 2. Sometimes, you may not want to delete the unreachable code for some reason. If you comment it out, it will no longer be compiled. This can result in a phenomenon called "bit rot."
Tip With pragma warning disable, you can keep the code compiling but eliminate the error as well.
using System; class Program { static void Main() { #pragma warning disable while (false) { int value = 1; if (value == 2) { throw new Exception(); } } #pragma warning restore } }
Reachability notes. Reachability in the C# language is carefully described in the specification. The reachability and unreachability of every statement is determined based on its end point.
End points. An end point is the location immediately after a statement. If the end point of a statement is reachable, the statement itself is reachable.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 22, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen