2007-11-20

C#中??的用法

改用c# 2.0也一年多了,
最近才發現??的用法.

??這個operator的用法如下

string message = null;
string result = message ?? "message is null";
Console.WriteLine(result); //列印出 message is null

 

string message = "I am not null";
string result = message ?? "message is null";
Console.WriteLine(result); // 列印出 I am not null

另外,在數值方面,

int x = null;

這樣是會產生編譯錯誤(Cannot convert null to 'int' because it is a non-nullable value type).
所以如果你就是要宣告一個int而可以是個null的內容的話,
那就是用

int? x = null;

再搭配??的用法如下

int? x = null;
int y = x ?? -1;
Console.WriteLine(y.ToString()); //列印出 -1

2 則留言:

非凡 提到...

ㄏㄏ .. Null 型別再 C# 2.0 中 , 也是一項重大的改變, 可能是你忙昏了頭 所以沒發現到唷^^"

不過說真的, 知道要用的人好像似乎也沒那麼多, 我們部門的人也是, 也是我發現後分享出來,大家才有開始在用的, 尤其是在接Request的時候也很好用.
string X=Request["xxx"] ?? string.Empty;

^^

AJ 提到...

to 非凡,
有好康的竟然不通知一下...
太不夠意思了...

當開發機是Windows on ARM...

 在MacOS上要使用windows去編譯一些程式常常會遇到一些plamform的問題... - cmake build failed 當使用 cmake -S . -B build 要建立 build system files 原本的專案是在x64上, 所以直接執行會直接使用A...