If DateTime is immutable, why does the following work?

The Now property is something like:

 DateTime Now {
     get {
         // Get the OS time
         return new DateTime(year, month, day, hour, min, sec...)
     }
 }

(technically false, the Now calls internally the UtcNow that calls the OS :-), but you get the idea).

The DateTime.Now is a factory for DateTime :-)


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.


You're simply telling the variable dt to refer to a different instance of DateTime. Under the hood, the DateTime.Now property generates a new DateTime instance every time you access it.

Tags:

C#

.Net

Datetime