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);
}
}
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); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With