Summary:
Null value type [Nullable value type]
1. A value type variable can never be null. It always contains the value itself. But in some cases, this may cause problems. For example, when designing a database, you can define the data type of a column as a 32-bit integer and map it to the Int32 data type of FCL. However, a column in the database is allowed to be null, and it may be quite difficult to use. Net Framework to process database data, because there is no way in CLR to express an Int32 value as null.
To solve this problem, Microsoft added the concept of nullable value type [System. Nullable <T>] In CLR.
Definition in CLR: public struct Nullable <T> where T: struct {...}
2. C # support for the null type
In C #, question mark is used to declare and initialize null variables:
Int32? X = 5;
Int32? Y = null;
3. C # null merge operator [?]
Obtain two operands. If the left operand is not null, return the value of this operand. If the left operand is null, return the value of the right operand. By using the null merge operator, you can easily set the default value of the variable.
One benefit of the null merge operator is that it can be used for both the reference type and the null type. For example:
Int32? B = null;
Int32 x = B ?? 123; // equivalent to: Int32 x = (B. HasValue )? B. Value: 123;
String temp = GetFilename ();
String filename = GetFilename ()?? "Untitled"; // equivalent to: filename = (temp! = Null )? Temp: "Untitled ";
4. Bind the null type.
When CLR loads a Nullable <T> instance, it checks whether it is null. If yes, the CLR will not perform any packing operations on it and directly return a null value. If the value of an empty instance is not null, CLR extracts the value from the instance and boxed it. That is to say, an Nullable <Int32> with a value of 5 is packed into Int32 with a value of 5.
Int32? X = 5;
Int32? Y = null;
Object o = y; // No packing operation is performed. The return value is null.
Console. WriteLine ("o is null = {0}", o = null); // "true"
Object o = x; // o references a boxed Int32
Console. WriteLine ("o's type is {0}", o. GetType (); // "System. Int32"
5. unbox the null type.
Object o = 5; // o references a boxed Int32
Int32 a = (Int32) o; // unpack it into an Int32
Int32? B = (Int32 ?) O; // unpack the package into an Nullable <Int32>
6. Call GetType through the null type.
When GetType is called on an Nullable <T> object, CLR actually returns the T type instead of the Nullable <T>, for example:
Int32? X = 5;
Console. WriteLine (x. GetType (); // display "System. Int32" instead of Nullable <Int32>