Reputation: 2785
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
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
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
Reputation: 1881
startDate.AddDays(1);
does not change startDate
, so startDate < endDate
is always true.
Upvotes: 0