C# if statement shorthand operators (? :) results in unreachable code
Why do I get this warning in C# with Visual Studio 2010?
"Unreachable expression code detect开发者_如何转开发ed"
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); }
}
DateTime is a value type, so it can never be null. Therefore, the test for == null evaluates to a constant false at compile time, so half of the ?: will never be reached at runtime.
The answers given already -- that a non-nullable value type will never be null, and therefore the comparison is known to return false at compile time -- are correct, you might be wondering about the obvious follow-up question: why is this even legal? That question has been asked many times on SO; the short version is that C# provides a "lifted" equality operator for every struct that provides an equality operator on the non-nullable type (if a lifted one does not exist already of course.)
That is to say, because DateTime provides an == operator, the compiler automatically generates an == operator on DateTime?, and that operator is applicable in your case.
That could be because DateTime
is a struct (value type) & not a reference type.
Hence, comparing it with null will always be false.
DateTime cannot be null
DateTime is not nullable, so its value will never be null.
精彩评论