TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Unreachable Code Detected

This C# article examines the unreachable code detected warning. It offers a solution.

Unreachable code is never executed.

The C# compiler issues an unreachable code detected warning. This warning can help you eliminate unused code. We look at unreachable code. We see how to eliminate this error but not remove the code.

Example. This 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. The "int value = 1" statement is never reached.

While

And: The compiler can figure this out before the program ever executes. It will generate an unreachable code detected warning.

Program with unreachable code: C#

using System;

class Program
{
    static void Main()
    {
	while (false)
	{
	    int value = 1;
	    if (value == 2)
	    {
		throw new Exception();
	    }
	}
    }
}

Compilation warning

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" or bugs over time.

Tip: With pragma warning disable, you can keep the code compiling but eliminate the error as well.

Pragma Directive

Using pragma to disable warnings: C#

using System;

class Program
{
    static void Main()
    {
    #pragma warning disable
	while (false)
	{
	    int value = 1;
	    if (value == 2)
	    {
		throw new Exception();
	    }
	}
    #pragma warning restore
    }
}

Compilation warnings
    (None.)

Summary. 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. An end point is the location immediately after a statement.

And: If the end point of a statement is reachable, the statement itself is reachable.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf