Reputation: 34158
I'm trying to make use for
on a DateTime
like this:
for (DateTime d = _BookedCheckIn; d <= _BookedCheckOut; d.AddDays(1))
{
// ...
}
But the problem is that d
does not increase. Does anyone have an idea of what the problem is?
Upvotes: 12
Views: 1433
Reputation: 7830
d.AddDays(1) does not actually add a day to d. It returns a new datetime object 1 day larger than d.
This problem has been documented here: https://stackoverflow.com/questions/380819/common-programming-mistakes-for-net-developers-to-avoid/1213588#1213588
Upvotes: 7
Reputation: 47530
Returns a new DateTime that adds the specified number of days to the value of this instance.
This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.
So... It should be as below
for (DateTime d = _BookedCheckIn; d <= _BookedCheckOut; d = d.AddDays(1))
Upvotes: 2
Reputation: 564413
You need to use:
for (DateTime d = _BookedCheckIn; d <= _BookedCheckOut; d = d.AddDays(1))
{
When you call d.AddDays
, it's returning a new DateTime, not changing the one you already created.
Upvotes: 21