If DateTime is immutable, why does the following work?

前端 未结 6 1490
轻奢々
轻奢々 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条回答
  •  Happy的楠姐
    2021-01-03 21:39

    The answer is simple. DateTime is not immutable. It is a struct. And I don't know how it's possible to have an immutable struct.

    If you do this:

    DateTime d1 = DateTime.Now;
    DateTime d2 = DateTime.Now;
    d1 = d2;
    

    Then, the struct d1 will be overwritten with d2's values.

    (A DateTime really only has one value. If you run a decompiler it is a private field called "ticks" I believe.)

    There is no reference stuff going on, or anything else funky.

提交回复
热议问题