The nullable types in C# are a unique data type to which you may assign a standard range of values as well as null values.
In a NullableInt32> variable, for example, you may store any value between -2,147,483,648 and 2,147,483,647 or null. In a Nullablebool> variable, you may also assign true, false, or null. The following is the syntax for defining a nullable type:
< data_type > ? < variable_name > = null;
Nullables at Show: , 45, , 3.14157 A Nullable boolean value:
With nullable value types and reference types, the null coalescing operator is employed. When an implicit conversion is available, it converts one operand to the type of another nullable (or not) value type operand.
If the first operand's value is null, the operator returns the value of the second operand; otherwise, the first operand's value is returned. The following example demonstrates this:
A nullable value type T? contains all of the values of its underlying value type T as well as a null value. You may give a bool? Variable any of the three values: true, false, or null, for example. T can't be a nullable value type because it's the underlying value type.
In C# 8.0, nullable reference types are a new feature. See Nullable reference types for additional details. Beginning with C# 2, nullable value types are supported.
The generic System is an instance of any nullable value type. T> structure that is nullable. Any of the following interchangeable forms can be used to refer to a nullable value type with an underlying type T: T or NullableT>?
When you need to represent the undefined value of an underlying value type, you usually use a nullable value type. A Boolean, or bool, variable, for example, can only be true or false.
However, in some applications, a variable value may be undefined or absent. For example, a database column might be true or false or NULL, which means it has no value. In that case, can you use the bool type?
Because a value type is automatically convertible to its equivalent nullable value type, you can assign a value to a nullable value type variable the same way you would for the underlying value type. The null value can also be assigned. Consider the following scenario:
C#
Null is represented as the default value of a nullable value type, which is an instance of NullableT>. The property HasValue returns false.
|