Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# if statement shorthand operators (? :) results in unreachable code

Why do I get this warning in C# with Visual Studio 2010?

"Unreachable expression code detected"

from the following code (DateTime.Now underlined in green squiggly):

public DateTime StartDate
{
  get
  {
    DateTime dt = (DateTime)ViewState["StartDate"];
    return ((dt == null) ? DateTime.Now : dt);
  }
}
like image 521
JohnB Avatar asked Aug 17 '10 18:08

JohnB


1 Answers

Because a DateTime struct can never be null.

If you're expecting a possible null value, you have to use a nullable DateTime struct. You could also use the null-coalescing operator instead of the conditional operator as well:

public DateTime StartDate
{
    get
    {
        DateTime? dt = (DateTime?)ViewState["StartDate"];
        return dt ?? DateTime.Now;
    }
}

Or you could do it as a one-liner (as in the comments):

public DateTime StartDate
{
    get { return (DateTime)(ViewState["StartDate"] ?? DateTime.Now); }
}
like image 162
Justin Niessner Avatar answered Oct 30 '22 03:10

Justin Niessner