C# 宣告變數時,型別帶"?"(問號),表示變數可接受null值

  • 5179
  • 0
int i2=null; //not ok
int? i4=null; //ok

bool flag1 = null; //not ok
bool? flag2 = null; //ok

 

It means a nullable type. The value can be null.

int? means, it is a "boxed" integer value. That means. a int? is nullable!

Like:

int value1 = 0; //you cannot do: int vlaue1 = nulll; it will be an error
//if you do:
int? vlaue2 = null; //will be ok!


int i1=1; //ok
int i2=null; //not ok
int? i3=1; //ok
int? i4=null; //ok


int? i = 10; //ok
double? d1 = 3.14; //ok
bool? flag = null; //ok
char? letter = 'a'; //ok
int?[] arr = new int?[10]; //ok

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?();

         // display the values
         Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4);
         Console.WriteLine("A Nullable boolean value: {0}", boolval);
         Console.ReadLine();
      }
   }
}

/*
relsult:
Nullables at Show: , 45,  , 3.14157
A Nullable boolean value:
*/

來源:
1. What does 'int?' mean?
https://social.msdn.microsoft.com/Forums/vstudio/en-US/4107d47b-b1c4-495d-a67a-6ad3f2e7adbc/what-does-int-mean?forum=csharpgeneral

2. https://www.tutorialspoint.com/csharp/csharp_nullables.htm
    節錄如下:"C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable."

3. 更詳盡的官方說明:使用可為 Null 的類型 (MSDN C# 程式設計手冊)
https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/nullable-types/using-nullable-types
    節錄如下:"如需可能使用可為 Null 類型的範例,請考慮一般的布林值變數如何能有兩個值︰true 和 false。 沒有任何表示「未定義」的值。 在許多程式設計應用程式最值得注意的資料庫互動中,變數會出現在未定義的狀態。 例如,資料庫的欄位可能包含值 true 或 false,但也可能完全不包含任何值。 同樣地,參考型別可以設為 null 以表示其尚未初始化。
    (For an example of when you might use a nullable type, consider how an ordinary Boolean variable can have two values: true and false. There is no value that signifies "undefined". In many programming applications, most notably database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.)"