Grahame A
Grahame A

Reputation: 3953

Using DateTime in a For loop, incrementing date Isn't working

I have this loop, its purpose is to loop through a range of dates and perform some logic to automate adding entries into the database. The issue is that the incrementing portion, date.AddDays(1.0) isn't working, and is always the same result, causing an infinite loop. Any insight?

for (DateTime date = DateTime.Now; futureDate.CompareTo(date) > 0; date.AddDays(1.0))
{
    // logic here
}

Upvotes: 28

Views: 42656

Answers (2)

Tim Robinson
Tim Robinson

Reputation: 54734

DateTime.AddDays returns a new instance without modifying date. At the moment you're throwing away this new instance. Instead, you need to do:

for (DateTime date = DateTime.Now; futureDate.CompareTo(date) > 0; date = date.AddDays(1.0))
{
    // logic here
}

Also, I'm not sure why you're calling CompareTo when you could use the < operator. I can't tell whether CompareTo(date) > 0 is correct without thinking about it for a moment, whereas the intent of the < operator is obvious:

for (DateTime date = DateTime.Now; date < futureDate; date = date.AddDays(1.0))
{
    // logic here
}

Upvotes: 74

Kirk Woll
Kirk Woll

Reputation: 77546

DateTime is immutable. Change to: date = date.AddDays(1.0)

Upvotes: 8

Related Questions