Consider this following code in C# 2.0
in fact it was complied like this:
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)
int? i = 1;
i++;
Console.WriteLine(i);
int? j = i;
j = null;
Console.WriteLine(j.HasValue);
i++;
Console.WriteLine(i);
int? j = i;
j = null;
Console.WriteLine(j.HasValue);
in fact it was complied like this:
1 Nullable<int> nullable1 = new Nullable<int>(1);
2 Nullable<int> nullable3 = nullable1;
3 nullable1 = nullable3.HasValue ? new Nullable<int>(nullable3.GetValueOrDefault() + 1) : new Nullable<int>();
4 Console.WriteLine(nullable1);
5 Nullable<int> nullable2 = nullable1;
6 nullable2 = new Nullable<int>();
7 Console.WriteLine(nullable2.HasValue);
2 Nullable<int> nullable3 = nullable1;
3 nullable1 = nullable3.HasValue ? new Nullable<int>(nullable3.GetValueOrDefault() + 1) : new Nullable<int>();
4 Console.WriteLine(nullable1);
5 Nullable<int> nullable2 = nullable1;
6 nullable2 = new Nullable<int>();
7 Console.WriteLine(nullable2.HasValue);
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)