I am receiving unreachable code detected in my properties. This worked for regular string fields but not for DateTime data type.
private DateTime m_RenewalDate;
public DateTime M_RenewalDate
{
get { return m_RenewalDate != null ? m_RenewalDate : DateTime.MinValue; }
set { m_RenewalDate = value; }
}
this is my sqldatareader
reader.GetDateTime(reader.GetOrdinal("M_RENEWALDATE"))
DateTime
is a value type, and can not be null. Therefore, the code in the getter is unreachable:
return m_RenewalDate != null ? // always evaluates to true
m_RenewalDate : // and therefore always returns this
DateTime.MinValue; // The code never hits this case.
If your field in the database can be null, perhaps you want to declare the property as a nullable DateTime: DateTime?
.
DateTime
is a value type and cannot be null. To compare with a null value in the database, use DBNull.Value
As driis said in his answer, m_RenewalDate == null
is always false as DateTime
is a value type and things declared to be value types cannot be null.
To have the get
the behavior of returning DateTime.MinValue
from M_RenewalDate
in the case that M_RENEWALDATE
is null
your reader code should look more like this
object renewalDate = reader.GetValue(reader.GetOrdinal("M_RENEWALDATE"));
if (Equals(renewalDate, DBNull.Value))
{
yourObject.M_RenewalDate = DateTime.MinValue;
}
else
{
yourObject.M_RenewalDate = (DateTime) renewalDate;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.