Document directory
4.7 create a value type that can be initialized as null.
Problem
You have a numeric variable used to control the values obtained from the database. The database may return a null value for this value. You need a simple method to store this value, or even return null.
Solution
The optional null type is used. There are two methods to create an empty type. The first method is to use? Type modifier:
Int? MyDBInt = null;
The second method is to use Nullable <T> generic type:
Nullable <int> myDBInt = new Nullable <int> ();
Discussion
Essentially, the following two statements are equivalent:
Int? MyDBInt = null;
Nullable <int> myDBInt = new Nullable <int> ();
In both declarations, myDBInt is considered to be of the null type and initialized to null. An empty type implements the InullableValue interface, which has only two attribute members: HasValue and Value. If the null type is set to null, The HasValue attribute returns false; otherwise, the return value is true. If HasValue returns true, you can access the Value attribute to obtain the Value currently stored in an empty data type. If an InvalidOperationException is thrown, this is because the Value attribute is not defined yet.
In addition, there are two methods to test the null type. First, use the HasValue attribute as follows:
If (myDBInt. HasValue)
Console. WriteLine ("Has a value:" + myDBInt. Value );
Else
Console. WriteLine ("Does not have a value (NULL )");
The second method is to compare with null:
If (myDBInt! = Null)
Console. WriteLine ("Has a value:" + myDBInt. Value );
Else
Console. WriteLine ("Does not have a value (NULL )");
Both methods are acceptable.
If you want to convert an empty type to a non-empty type, the conversion operation is normal. If the empty type is set to null, an InvalidOperationException is thrown. When a non-empty type is converted to an empty type, the conversion operation runs normally without the InvalidOperationException. The non-empty type is never null.
It should be noted that the null type is used for comparison. For example, when you execute the following code:
If (myTempDBInt <1, 100)
Console. WriteLine ("myTempDBInt <100 ");
Else
Console. WriteLine ("myTempDBInt >=100 ");
The Code "myTempDBInt <100" is obviously incorrect. To fix it, you have to check whether myTempDBInt is empty. If not, the code block in the if statement can be executed:
If (myTempDBInt! = Null)
{
If (myTempDBInt <1, 100)
Console. WriteLine ("myTempDBInt <100 ");
Else
Console. WriteLine ("myTempDBInt >=100 ");
}
Else
{
// Handle null values here
}
Another interesting thing is that you can use an empty type like a common number, for example:
Int? DBInt = 10;
Int Value = 2;
Int? Result = DBInt + Value; // Result = 12
If the null type in the expression is a null value, the result of the expression is null, but if the value of the non-null type is null, the operator treats it as a general type. In the preceding example, if DBInt is null, the Result is also null.