Reputation: 36654
I have the following for loop:
for (DateTime dateTime = FromDate; dateTime.CompareTo(ToDate) < 1; dateTime.AddDays(1)) { .. }
While debugging I see the dateTime.AddDays(1) is executed but doesn't change the dateTime. Any predictable reason ?
Upvotes: 2
Views: 95
Reputation: 12304
From the msdn documentation:
This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.
Upvotes: 0
Reputation: 22094
dateTime.AddDays(1)
will not change the value of dateTime
. It will return a new object with the new data.
Upvotes: 1
Reputation: 10147
AddDays method returns a new date, so you should have something like this: dateTime=dateTime.AddDays(1)
Upvotes: 1
Reputation: 60694
AddDate returns a new DateTime where the date is added. You have to change it to this
for (DateTime dateTime = FromDate; dateTime.CompareTo(ToDate) < 1; dateTime = dateTime.AddDays(1)) { .. }
Upvotes: 1
Reputation: 1062780
AddDays
returns a new date - it doesn't change the existing value (it is immutable)
You could perhaps use:
dateTime = dateTime.AddDays(1)
For the middle term, you might also find dateTime < ToDate
easier to read (at a glance) than CompareTo
.
Upvotes: 3