Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If DateTime is immutable, why does the following work?

Tags:

I thought I understood what Immutable meant, however I don't understand why the following compiles and works:

DateTime dt = DateTime.Now;  Console.WriteLine(dt); 

Copy and paste the next part a few times

dt = DateTime.Now; Console.WriteLine(dt); Console.ReadLine(); 

As expected, it runs, and when I press enter, it then displays the next time... I thought this was not possible and I would need to create a new object. Why is this allowed/working? Or, is the book I am working from wrong and DateTime is not immutable (However I have read this on several sources)?

like image 528
Wil Avatar asked Feb 19 '11 17:02

Wil


People also ask

Is DateTime immutable?

The DateTime object itself is immutable, but not the reference dt. dt is allowed to change which DateTime object it points to. The immutability refers to the fact we can't change the variables inside a DateTime object.

Is Python DateTime immutable?

Since all available types in the datetime module are documented as being immutable (right after the documentation of the classes it is stated): Objects of these types are immutable. you shouldn't worry about this.


1 Answers

The DateTime object itself is immutable, but not the reference dt. dt is allowed to change which DateTime object it points to. The immutability refers to the fact we can't change the variables inside a DateTime object.

For example, we can't go

dt.Day = 3; 

dt itself is just a reference variable that points towards a DateTime object. By its definition, it's allowed to vary.

As pst mentioned, though, readonly and const are probably closer to what you're thinking, where you can't change the value of a variable.


Side note: DateTime is a Structure, and therefore, a value type, and I'm being misleading by calling dt a 'reference.' However, I think it still holds true that dt is still just a variable 'pointing' at an immutable object, and the variable itself is still mutable. Thanks to dan04 for pointing that out.

like image 128
Zach L Avatar answered Nov 09 '22 13:11

Zach L