Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Nullable description


May 11, 2021 C#


Table of contents


Nullable

It provides a special data type, the nullable type (empty type), that can represent a value in the normal range of its underlying value type, plus an null value.

For example, any value between -2,147,483,648 and 2,147,483,647, read as "empty Int32", can also be assigned a null value. Similarly, Nullable-lt; bool-and-bt; variables can be assigned to true or false or null.

The ability to assign null to numeric types or Boolean types is especially 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 a value of true or false, or it can be undefined.

The syntax for declaring an nullable type (empty type) is as follows:

<data_type> ? <variable_name> = null;

The following example demonstrates the use of empty 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 merge operator (??

Null merge operators are used to define default values for empty and reference types. T he Null merge operator defines a preset value for type conversion in case the nullable type value is Null. The Null merge operator implicitly converts the operatic type to the type of operandi of another value type that can be empty (or not).

If the value of the first operand is null, the operator returns the value of the second operand, otherwise the value of the first operand is returned. 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