LoginSignup
1
2

More than 5 years have passed since last update.

SQLのCOALESCEと同じステートメント

Last updated at Posted at 2015-02-10

?? 演算子

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?

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2