Elad Benda
Elad Benda

Reputation: 36654

For loop with date as iterator

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

Answers (5)

Nathan
Nathan

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

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

dateTime.AddDays(1) will not change the value of dateTime. It will return a new object with the new data.

Upvotes: 1

Ruslan
Ruslan

Reputation: 10147

AddDays method returns a new date, so you should have something like this: dateTime=dateTime.AddDays(1)

Upvotes: 1

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

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

Marc Gravell
Marc Gravell

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

Related Questions