Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

For-loop and DateTime Problem

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

Answers (4)

Scott Ferguson
Scott Ferguson

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

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28718

Or alternatively

d += TimeSpan.FromDays(1);

Upvotes: 1

CharithJ
CharithJ

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.

MSDN

So... It should be as below

for (DateTime d = _BookedCheckIn; d <= _BookedCheckOut; d = d.AddDays(1))

Upvotes: 2

Reed Copsey
Reed Copsey

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

Related Questions