If DateTime is immutable, why does the following work?

前端 未结 6 1460
轻奢々
轻奢々 2021-01-03 20:34

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

DateTime dt = DateTime.Now;

Console.WriteLine         


        
6条回答
  •  情话喂你
    2021-01-03 21:28

    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.

提交回复
热议问题