Consider this following code in C# 2.0
Nullable Type is an immutable type            int? i = 1;
Nullable Type is an immutable type            i
++;
Nullable Type is an immutable type            Console.WriteLine(i);
Nullable Type is an immutable type            
int? j = i;
Nullable Type is an immutable type            j 
= null;
Nullable Type is an immutable type            Console.WriteLine(j.HasValue);

in fact it was complied like this:
1Nullable Type is an immutable type      Nullable<int> nullable1 = new Nullable<int>(1);
2Nullable Type is an immutable type      Nullable<int> nullable3 = nullable1;
3Nullable Type is an immutable type      nullable1 = nullable3.HasValue ? new Nullable<int>(nullable3.GetValueOrDefault() + 1) : new Nullable<int>();
4Nullable Type is an immutable type      Console.WriteLine(nullable1);
5Nullable Type is an immutable type      Nullable<int> nullable2 = nullable1;
6Nullable Type is an immutable type      nullable2 = new Nullable<int>();
7Nullable Type is an immutable type      Console.WriteLine(nullable2.HasValue);Nullable Type is an immutable type

please note line 3, when we increased the nullable i, it actually created a new instance of Nullable<int>
     new Nullable<int>(nullable3.GetValueOrDefault() + 1)
and in line 6, when we assign null to a nullable instance, it also created a new instance with null value.
    nullable2 = new Nullable<int>();

Once we created an instance of Nullable<T>, we can NOT modify the inner value any more. When we modify these value, we  actually create a new instance with the new value. Nullable<T> is an immutable type.

It looks like string, right? (though Nullable<T> is a value type)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-26
  • 2021-10-01
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-22
  • 2021-05-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-12-19
相关资源
相似解决方案