23

I have this simple program:

        DateTime aux = new DateTime(2012, 6, 12, 12, 24, 0);
        DateTime aux2 = new DateTime(2012, 6, 12, 13, 24, 0);
        aux2.AddDays(1);

       Console.WriteLine((aux2 - aux).TotalHours.ToString());

        Console.ReadLine();

I debugged this and found aux2.AddDays(1); doesn't seem to work, what am I missing here? it should return 25 but the answer is one.

What is the problem?

also AddHours doesn't work, I guess that the others aren't working too.

Necrolis
  • 25,836
  • 3
  • 63
  • 101
Sas Gabriel
  • 1,544
  • 2
  • 20
  • 27
  • 8
    `DateTime` instances are immutable. You have to assign the result of `.AddDays` to another instance (or to itself). – mellamokb Jul 20 '12 at 16:43

3 Answers3

65

It does work but you don't do anything with the return value, try

aux2 = aux2.AddDays(1);

DateTimes share this facet of immutability with Strings.


EDIT

There is a little paragraph about it on MSDN

This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
5

DateTime.AddDays returns new DateTime that adds specified number of days. You need to assign it to your variable:

aux2 = aux2.AddDays(1);
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
0

You are working with immutable functions.

The DateTime function is immutable, once you set variable equal to it, it cannot change, you can though set new variables equal to a working of the function. The AddDay function takes the variable you put into it, but it does not change the original variable, that remains immutable. So you need to set a new variable equall to the original variable + a day.

So all you really need to do is change

aux2.AddDays(1);

to

aux2 = aux2.Adddays(1);

and then the rest of your comparison functions should work

Neil Meyer
  • 473
  • 4
  • 15
  • This behaviour is not associated with the immutability of the function. The immutability of the type or, in this case, the structure is what matters. – Jodrell Oct 26 '21 at 08:42