r0bb077
r0bb077

Reputation: 752

AddDays() not working within a while loop

Is there anything that stops the DateTime AddDays() method that doesn't run within a while loop. I have this simple bit of code;

DateTime last_day = monthCalendar2.SelectionRange.End;
DateTime first_day = new DateTime(year, month, day);

//Insert dates into vector
while (first_day != last_day)
{
  dates.Add(first_day);
  first_day.AddDays(1);
}

I step through the program and first_day never changes, anyone know why?!

Upvotes: 3

Views: 4201

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

DateTime is immutable. You should do

first_day = first_day.AddDays(1);

UPDATE: If you check DateTime.AddDays method description: Returns a new System.DateTime that adds the specified number of days to the value of this instance. That relates to all operations (such as Add, Substract, AddHours etc) on DateTime structure - any calculation does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation. That's because DateTime is immutable struct. I.e. instance value cannot be changed after it was created.

Upvotes: 11

Ian
Ian

Reputation: 34489

The reason being is that DateTime is Immutable, this means that you can't directly modify it and instead need to create a new instance of it. Strings are another type that behave in this way which you may be more used to.

first_day = first_day.AddDays(1);

Upvotes: 15

Peter Davidsen
Peter Davidsen

Reputation: 678

DateTime can't be changed, so instead do.

first_day = first_day.AddDays(1);

Upvotes: 4

Related Questions