23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# の null条件演算子 null合体演算子の使用例メモ

23
Last updated at Posted at 2020-06-10

null なんちゃら演算子の使い方がいつも迷うので、自分用に超簡単メモφ(..)
(オブジェクトや変数の型の明示とか省略)

null条件演算子【 ?. 】

var name = person?.name;

person が null の場合は name は null。
person が null でない場合のみ person.name を返す。
これは下記のコードと等価。

var name = "";
if (person == null)
  name = null;
else
  name = person.name;

null合体演算子【 ?? 】

var name = personName ?? "personName is null";

personName が null の場合でも name に 何か ("personName is null") 代入したい。
personName が null でない場合は、name に personName がそのまま代入される。
これは下記のコードと等価。

var name = "";
if (personName == null)
  name = "personName is null";
else
  name = personName;

null条件演算子 と null合体演算子 の合わせ技

とあるオブジェクトのメンバ変数を取得したいけど、もしそのオブジェクトが null だった場合に既定値をぶち込む、的な用途に使うといい感じっぽい。

var name = person?.name ?? "person is null";

(person が null の時、person?.name は null なので ?? の右側が評価される)
これは下記のコードと等価

var name = "";
if (person == null)
  name = "person is null";
else
  name = person.name;

※ 2020/06/12 追記
コメントにてご指摘頂きましたので追記します。
上記コードで person は null ではないが person.name が null の場合も person is null が返りますね。
できるだけシンプルに解釈できるようにサラッと書いてしまったので不正確でした。
等価コードは下記のような感じでしょうか。

var name = "";
if (person != null && person.name != null)
  name = person.name;
else
  name = "person or person.name is null";

参考にさせていただい記事

いつも有難うございます。

23
22
1

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
23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?