user1027620
user1027620

Reputation: 2785

Infinite Loop during while

Why is this running indefinitely and not adding days

var startDate = new DateTime(year, 1, 1);
var endDate = startDate.AddYears(1);

while (startDate < endDate)
{
    startDate.AddDays(1);
}

The goal is to loop through all the days in a year.

Thanks!

Upvotes: 1

Views: 101

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

In order to avoid such pesky errors (not assigning back AddDays(1) result) I suggest implementing for loop instead of while:

  for (var date = new DateTime(year, 1, 1); 
           date < new DateTime(year + 1, 1, 1); 
           date = date.AddDays(1)) {
    ...
  }

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26836

In .NET DateTime is immutable, so AddDays method just returns new date, not changes startDate itself.

You should assign this new value back to startDate:

startDate = startDate.AddDays(1);

Upvotes: 9

Paul Chen
Paul Chen

Reputation: 1881

startDate.AddDays(1); does not change startDate, so startDate < endDate is always true.

Upvotes: 0

Related Questions