Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable DateTimes and the AddDays() extension

Tags:

c#

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

Nullable<DateTime> does not have a definition for AddDays

. Is there any way to resolve this error?

DateTime? lastInvite = (DateTime?)Session["LastInviteSent"];

if ((string)Session["InviteNudgeFlag"] == "False" && ((lastInvite == null && DateTime.Now >= AcctCreation.AddDays(7)) || (int)Session["InviteCount"] > 0 && DateTime.Now >= lastInvite.AddDays(7)))
{
   // Non important code here
}
like image 903
Rex_C Avatar asked Aug 29 '13 18:08

Rex_C


1 Answers

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;
}
like image 178
Dustin Kingen Avatar answered Sep 22 '22 16:09

Dustin Kingen