Home > Article > Backend Development > [C# Tutorial] C# Nullable Type (Nullable)
C# Nullable type (Nullable)
C# Nullable type (Nullable)
C# provides a special data type, nullable type (nullable type), nullable type can Represents a value within the normal range of its underlying value type, plus a null value.
For example, Nullablecd36f3a10e893bd0816cde352a4c0370, pronounced "nullable Int32", can be assigned to any value between -2,147,483,648 and 2,147,483,647, or can be assigned to the null value. Similarly, Nullableac0be6af5062419877ecf85863349134 variables can be assigned true or false or null.
The ability to assign null to numeric or Boolean types 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 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 use 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 When compiled and executed, it produces the following results:
显示可空类型的值: , 45, , 3.14157 一个可空的布尔值:
Null Coalescing Operator ( ?? )
Null Coalescing Operator is used to define default values for nullable and reference types. 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.
The operator returns the value of the second operand if the value of the first operand is null, 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 will produce the following results:
num3 的值: 5.34 num3 的值: 3.14157
The above is [c# tutorial] C# Nullable type (Nullable ), please pay attention to the PHP Chinese website (www.php.cn) for more related content!