I have a DateTime variable that can either be null or a Datetime. I figured a nullable DateTime type would work, but I am getting an error telling me that said
If you look at the documentation for the Nullable<T> type, you'll see it only has a few members. The Value
member will get you the T
inside, if the Nullable<T>
container has a value. The Nullable<T>
doesn't borrow any members from the type T
it wraps.
You need to go through the "Value" property:
lastInvite.Value.AddDays(7)
Note that this will throw an exception if the DateTime is actually null. Luckily, there is another property you can use to test for this, "HasValue".
if (lastInvite.HasValue){ /* code */ }
There are multiple ways to resolve this error.
Use Convert.ToDateTime()
method which handles null datetime values.
Convert.ToDateTime(lastInvite).AddDays(7);
Use Value
property
lastInvite.Value.AddDays(7)
Use GetValueOrDefault()
method
lastInvite.GetValueOrDefault().AddDays(7)
You should consider trying to make your logic more readable:
var inviteNudgeFlag = bool.Parse((string) Session["InviteNudgeFlag"]);
if(!inviteNudgeFlag)
{
return;
}
var lastInvite = (DateTime?) Session["LastInviteSent"];
var inviteCount = (int) Session["InviteCount"];
var numOfDays = 7;
var now = DateTime.Now;
var weekSinceLastInvite = lastInvite.HasValue
? now >= lastInvite.Value.AddDays(numOfDays)
: now >= AcctCreation.AddDays(numOfDays);
var hasInvites = !lastInvite.HasValue || inviteCount > 0;
var canInvite = hasInvites && weekSinceLastInvite;
if(!canInvite)
{
return;
}