LoginSignup
9
3

More than 5 years have passed since last update.

C#のNullable型で三項演算子を使うときの注意

Last updated at Posted at 2019-03-05

はじめに

C#のNullable型で三項演算子を使おうと思ったらコンパイルエラーになったので、備忘録としてメモを残しておく。
ちなみに三項演算子を使いたかった理由は、三項演算子の方が可読性が高まるケースがあっためです。
(本記事は三項演算子の良し悪しについて議論したいわけではありません)

エラー内容

以下のコードはコンパイルエラーになります。

int? num = true ? 1 : null;

error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

エラーメッセージを意訳すると、

三項演算子の第二オペランドの型と第三オペランドの型が異なるうえに、nullはintに暗黙的な型変換ができないよ

とのこと。

そもそも三項演算子は第二オペランドと第三オペランドを同じ型にする必要があります。
そのうえで、さらにnullはintに暗黙的な型変換ができないので、上記のように怒られているようですね。

解決策1

nullからNullable<int>へ明示的に型変換すれば、Nullable<int>からintへは暗黙的に型変換してくれるので実行可能になります。

int? num = true ? 1 : (int?)null;

解決策2

そもそも三項演算子にこだわらずifで書けば、もちろん問題ないですね。

int? num = null;
if (true) {
    num = 1;
}

参考リンク

9
3
4

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
9
3