A nullable type is an instance of the system.nullable structure. A nullable type can represent a value that is within the normal range of its underlying value type, plus a null value. For example, Nullable<int32>, read as "Nullable Int32", can be assigned to any value between 2147483648 and 2147483647, or it can be assigned a null value. The nullable<bool> can be assigned a value of true or false, or null. The ability to assign null to a numeric type or Boolean is particularly useful when working with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store a value of true or false, or the field may not be defined.
C#class Nullableexample
{
static void Main ()
{
Int? num = null;
if (Num. HasValue = = True)
{
System.Console.WriteLine ("num =" + num.) Value);
}
Else
{
System.Console.WriteLine ("num = Null");
}
Y is set to zero
int y = num. GetValueOrDefault ();
Num. Value throws an InvalidOperationException if Num. HasValue is False
Try
{
y = num. Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine (E.message);
}
}
}
The above will show the output:
num = Null
Nullable object must has a value.
Overview of nullable types
Nullable types have the following characteristics:
A nullable type represents a value type variable that can be assigned a value of null . You cannot create a nullable type based on a reference type. (The reference type already supports null values.) )。
Syntax T? is a shorthand for system.nullable<t>, where t is a value type. These two forms are interchangeable.
Assigning a value to a nullable type is the same as assigning a value to a generic value type, such as int? x = ten; Or double? d = 4.108;.
If the value of the underlying type is null, use the System.Nullable.GetValueOrDefault property to return the value or default value assigned to the underlying type, such as int j = X.getvalueordefault ();
Use the HasValue and value read-only properties to test if null and retrieve values, such as if (x.hasvalue) j = x.value;
If this variable contains a value, the HasValue property returns True, or False if the value of this variable is null.
If the value is assigned, The Value property returns this, or System.InvalidOperationException is thrown.
The default value of the nullable type variable sets HasValue to false. Valueis not defined.
Use the ?? operator to assign a default value, and the nullable type with the current value of NULL is assigned to a non-null type when the default value is applied, such as int? x = null; int y = x??-1;
The use of nested nullable types is not allowed. The following line will not be compiled:nullable<nullable<int>> N;
Using nullable types
Nullable types can represent all values of the underlying type, and can also represent null values. Nullable types can be declared in one of the following two ways:
System.nullable<t> variable
Or
T? Variable
T is the underlying type of a nullable type. T can be any value type, including a struct, but cannot be a reference type.
For an example that might use a nullable type, consider how a normal Boolean variable can have two values: True and False. There is no value that represents "undefined." In many programming applications (most notably database interaction), variables can exist in undefined states. For example, a field in a database may contain a value of true or FALSE, but it may also not contain a value at all. Similarly, reference types can be set to NULL to indicate that they are not initialized.
This inconsistency results in additional programming work, such as using additional variables to store state information, using special values, and so on. The nullable type modifier enables C # to create a value type variable that represents an undefined value.
Examples of nullable types
Any value type can be used as the basis for a nullable type. For example:
C#
Int? i = 10;
Double? D1 = 3.14;
bool? flag = NULL;
Char? letter = ' a ';
Int? [] arr = new int? [10];
Members of nullable types
Each instance of a nullable type has two public read-only properties:
HasValue
The HasValue belongs to the bool type. When a variable contains a non-null value, it is set to true.
Value
The type of Value is the same as the underlying type. If HasValue is true, then value contains a meaningful value. If HasValue is false, accessing Value will raise InvalidOperationException.
In this example, the HasValue member is used to test whether a variable contains a value before attempting to display it.
C#
Int? x = 10;
if (X.hasvalue)
{
System.Console.WriteLine (X.value);
}
Else
{
System.Console.WriteLine ("Undefined");
}
You can also test whether a value is included by using the following method:
C#
Int? y = 10;
if (Y! = null)
{
System.Console.WriteLine (Y.value);
}
Else
{
System.Console.WriteLine ("Undefined");
}
An explicit conversion
Nullable types can be cast to regular types by using casts for explicit conversions or by using the Value property. For example:
C#
Int? n = null;
int m1 = n; would not compile.
int m2 = (int) n; Compiles, but would create an exception if x is null.
int m3 = N.value; Compiles, but would create an exception if x is null.
If a user-defined conversion is defined between two data types, the same transformation can also be used for a nullable version of these data types.
Implicit conversions
You can use the NULL keyword to set the nullable type variable to NULL, as follows:
C#
Int? N1 = null;
Conversions from normal types to nullable types are implicit.
C#
Int? N2;
N2 = 10; Implicit conversion.
Operator
Nullable types can also use predefined unary and two-tuple operators, as well as any existing user-defined value type operators. If the operands are empty, the operators will produce a null value, otherwise the operator will use the included values to evaluate the result. For example:
C#
Int? A = 10;
Int? b = null;
a++; Increment by 1, now a is 11.
A = a * 10; Multiply by ten, now A is 110.
A = a + B; Add B, now A is null.
When you perform a comparison of nullable types, if any of the nullable types are null, the comparison result will always be false. Therefore, it is important not to assume that the opposite is true because a comparison result is false. For example:
C#
Int? NUM1 = 10;
Int? num2 = null;
if (NUM1 >= num2)
{
System.Console.WriteLine ("NUM1 is greater than or equal to NUM1");
}
Else
{
NUM1 is isn't less than num2
}
The conclusion in the Else statement above is invalid because num2 is null, so it does not contain a value.
?? Operator
?? The operator defines the default value that is returned when a nullable type is assigned to a non-nullable type.
C#
Int? c = null;
D = c, unless c is null, in which case d =-1.
int d = c?? -1;
This operator can also be used with multiple nullable types. For example:
C#
Int? e = null;
Int? f = null;
g = e or F, unless E and F is both null, in which case g =-1.
int g = e?? F?? -1;
bool? Type
bool? A nullable type can contain three different values: true, FALSE, and null. They cannot be used in a conditional statement, such as if, for, or while. For example, the following code fails to compile and will report compiler error CS0266:
bool? b = null;
if (b)//Error CS0266.
{
}
This is not allowed because null means nothing in the context of the condition. To be able to be used in a conditional statement, a nullable Boolean value can be cast explicitly to bool, but if the object has a value of NULL, InvalidOperationException is thrown. Therefore, it is important to check the HasValue property before casting to bool.
A nullable Boolean value is similar to the type of Boolean variable used in SQL. To ensure & and | The operator produces a result that is consistent with the three-valued Boolean type of SQL, and provides the following predefined operators:
bool? Operator & (bool x, bool y)
bool? operator | (bool x, bool y)
The results of these operators are listed in the following table:
X |
y |
X&y |
X|y |
True |
True |
True |
True |
True |
False |
False |
True |
True |
Null |
Null |
True |
False |
True |
False |
True |
False |
False |
False |
False |
False |
Null |
False |
Null |
Null |
True |
Null |
True |
Null |
False |
False |
Null |
Null |
Null |
Null |
Null |
C # Nullable types