Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

c# - How can I fix the error : "Unreachable Code Detected"

public partial class KalenderLeeftijd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void calBirthDate_SelectionChanged(object sender, EventArgs e)
{

}
private string GetAnswer()
{
    DateTime birthday = calBirthDate.SelectedDate;
    TimeSpan difference = DateTime.Now.Date - birthday;
    int leapYears = CountLeapYears(birthday);

    int days = (int)difference.TotalDays - leapYears;
    int hours = (int)difference.TotalHours - leapYears * 24;

    int years = days / 365;

    String answer = String.Format("Age: {0} years", years);
    answer += Environment.NewLine;
    answer += String.Format("Days: {0}*365+{1} = {2}", years, days - years * 365, days);
    answer += Environment.NewLine;
    answer += String.Format("Days Hours: {0}*24 = {1}", hours / 24, hours);
    return answer;
}

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;
    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();

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...