views:

60

answers:

2

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
}
+12  A: 

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
}
Tim Robinson
Thanks, I JUST noticed this. The loop appears to be working correctly now, thanks.
Gallen
+3  A: 

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

Kirk Woll