class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
static void Main()
{
int? x = null;
// x が null でなければ y に x が代入される。このケースでは -1 になる。
int y = x ?? -1;
// メソッドの戻り値 が null でなければ i に 戻り値 が代入される。このケースでは default(int) (=0) になる。
int i = GetNullableInt() ?? default(int);
// ?? は参照型でも有効。このケースでは Unspecified が出力される。
string s = GetStringValue();
Console.WriteLine(s ?? "Unspecified");
}
}
Linqを使う方法もある(Coalesceメソッドのところ)
?? Coalesce for empty string?