SoFunction
Updated on 2025-03-07

C# nullable type analysis

For example, Nullable<Int32>, read "Nullable Int32", can be assigned a value of any value between -2147483648 and 2147483647, or can be assigned a value of null. Nullable<bool> can be assigned to true or false, or null. The ability to assign null to a numeric type or a boolean type is particularly useful when working with databases and other data types that contain elements that may not be assigned. For example, a Boolean field in a database can store the value true or false, or the field can also be undefined.
The nullable type has the following characteristics:
·The nullable type represents a value type variable that can be assigned a null value. Unable to create a nullable type based on a reference type. (The reference type supports null values.).
·Syntax T? is the abbreviation of <T>, where T is the value type. These two forms are interchangeable.
·Assigning values ​​to nullable types is the same as assigning values ​​to general value types, such as int? x = 10; or double? d = 4.108;.
·If the value of the base type is null, please use the attribute to return the value or default value assigned by the base type, for example, int j = ();
·Please use HasValue and Value read-only properties to test whether it is empty and retrieve the value, for example if() j = ;
If this variable contains a value, the HasValue property returns True; or, if the value of this variable is empty, returns False.
If a value has been assigned, the Value property returns the value, otherwise it will be raised.
The default value of a nullable type variable sets HasValue to false. Value not defined.
·Use the ?? operator to assign the default value. When the nullable type with the current value is assigned to a non-empty type, the default value will be applied, such as int? x = null; int y = x ?? -1;.
·Nested nullable types are not allowed. The following line will not be compiled: Nullable<Nullable<int>> n;
Program code Program code
class NullableExample
{
static void Main()
{
int? num = null;
if ( == true)
{
("num = " + );
}
else
{
("num = Null");
}
//y is set to zero
int y = ();
// throws an InvalidOperationException if is false
try
{
y = ;
}
catch ( e)
{
();
}
}
}
The above will display the output:
num = Null
Nullable object must have a value.