Since a value type variable can never be null, and a column in the database allows null values, CLR introduces a null type to correspond to columns in the database.
C # declares and initializes the null type in question mark notation, as shown in the following code:
#001 Int? X = 5; #002 Int? Y = NULL; |
C # allows data conversion and transformation of the null type. The sample code is as follows:
#001 Int? X = 5; #002 int z = (INT) X; |
You can bind a null value type. The rule is: if the null type is null, the CLR does not perform the packing operation and returns the null value. If it is not null, it is packed. The sample code is as follows:
#001 static void nulltoobject () #002 { #003 Int? B = NULL; #004 object o = B; #005 console. writeline ("O is null = {0}", O = NULL); // result o is null = ture #006 B = 5; #007 o = B; #008 console. writeline ("O's type = {0}", O. GetType ()); #009 // result O's type = system. int32 #010} |
In this example, if the first result o is null = true, an error is returned when o. GetType () is called immediately.
You can unpack null values. CLR allows a boxed value type T to be split into a T or an nullable. The sample code is as follows:
#001 static void objecttonull () #002 { #003 Ob Ject o = 5; #004 Int? A = (Int ?) O; #005 int B = (INT) O; #006 console. writeline ("A = {0}, B = {1}", a, B); // result a = 5, B = 5 #007 o = NULL; # 008 A = (Int ?) O; #009} |
If B = (INT) O; is added under row 8, an error of null reference is returned.
You can call the GetType () method by using the null value type. The result is of the system. int32 type instead of the Systems. nullable <int32> type.
When an interface method can be called with a null value, nullable does not implement the icomparable interface like int32, but CLR allows the following code to be compiled.
#001 static void nulluseinterface () #002 { #003 Int? A = 5; #004 int B = (icomparable) a). compareto (5); // compile #005 console. writeline (B); // The result is 0. #006} |