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)?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With