7

I have the following code:

private string GetAnswer()
{
   ....
}

private int CountLeapYears(DateTime startDate)
{
    return count;
    String answer = GetAnswer();
    Response.Write(lblAntwoord); 
}

Why do I get the error :

Unreachable code detected

The error is shown on the following line String answer = GetAnswer();

Liam
  • 27,717
  • 28
  • 128
  • 190
Tim van Laere
  • 111
  • 1
  • 1
  • 3

4 Answers4

36

It's just because your code comes after the return statement.

The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.

If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method.

http://msdn.microsoft.com/en-us/library/1h3swy84%28v=vs.100%29.aspx

solution (obvious) :

move the unreachable code before the return statement.

Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
9

Unreachable code is a compiler warning, not error. You have three options:

It is unreachable because the flow of the method exits at the return statement, and thus will never execute the code below. The compiler can determine this and so can report it. Like I said, these are actually compiler warnings and won't stop a successful build unless you have configured the project to treat warnings as errors.

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
2

The statement:

return count;

Exits the function. Therefore,

answer = GetAnswer(); 
Response.Write(lblAntwoord);  

cannot be reached.

Glen Thomas
  • 10,190
  • 5
  • 33
  • 65
Larry
  • 17,605
  • 9
  • 77
  • 106
0

The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed

In Your Code :

private int CountLeapYears(DateTime startDate)
{
    int count = 0;
    for (int year = startDate.Year; year <= DateTime.Now.Year; year++)
    {
        if (DateTime.IsLeapYear(year))
        {
            DateTime february29 = new DateTime(year, 2, 29);
            if (february29 >= startDate && february29 <= DateTime.Now.Date)
            {
                count++;
            }
        }
    }
    return count;//The Execution will be terminated here,the next lines will become unreachable 
    **String** answer = GetAnswer();
    Response.Write(lblAntwoord); 
}
}

MSDN LINK :

C : https://msdn.microsoft.com/en-us/library/sta56yeb.aspx

c# : https://msdn.microsoft.com/en-us/library/1h3swy84.aspx

Community
  • 1
  • 1
Venkat
  • 2,549
  • 2
  • 28
  • 61