C# nullable types
#C# Nullable type (Nullable)
C# provides a special data type, nullable type (nullable type) , a nullable type can represent values within the normal range of its underlying value type, plus a null value.
For example, Nullable<Int32>, pronounced as "nullable Int32", can be assigned to any value between -2,147,483,648 and 2,147,483,647, and can also be assigned to the null value. Similarly, Nullable< bool > variables can be assigned true or false or null.
The ability to assign null to numeric or Boolean types is particularly useful when dealing 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 the values true or false, or the field can be undefined.
The syntax for declaring a nullable type (nullable type) is as follows:
< data_type> ? <variable_name> = null;
The following example demonstrates the usage of nullable data types:
using System; namespace CalculatorApplication { class NullablesAtShow { static void Main(string[] args) { int? num1 = null; int? num2 = 45; double? num3 = new double?(); double? num4 = 3.14157; bool? boolval = new bool?(); // 显示值 Console.WriteLine("显示可空类型的值: {0}, {1}, {2}, {3}", num1, num2, num3, num4); Console.WriteLine("一个可空的布尔值: {0}", boolval); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following results:
显示可空类型的值: , 45, , 3.14157 一个可空的布尔值:
Null coalescing operator (??)
Null coalescing operator is used to define nullable types and references The default value of the type. The Null coalescing operator defines a default value for type conversion in case the value of a nullable type is Null. The Null coalescing operator implicitly converts the operand type to another nullable (or non-nullable) value type.
If the value of the first operand is null, the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example demonstrates this:
using System; namespace CalculatorApplication { class NullablesAtShow { static void Main(string[] args) { double? num1 = null; double? num2 = 3.14157; double num3; num3 = num1 ?? 5.34; Console.WriteLine("num3 的值: {0}", num3); num3 = num2 ?? 5.34; Console.WriteLine("num3 的值: {0}", num3); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following results:
num3 的值: 5.34 num3 的值: 3.14157