プログラミング言語C#における条件演算子(conditional operator) ?: と、子クラスから親クラスへの型推論に関してメモ。
条件演算子の第2, 3項目に親クラスParentから派生した子クラスChild1, Child2を指定した場合、C#では型推論に失敗してコンパイルエラーとなる。(両者の共通型Parentへの推論は行われない)
class Parent {} class Child1 : Parent {} class Child2 : Parent {} bool b = /*...*/: Child1 c1 = new Child1(); Child2 c2 = new Child2(); var r = b ? c1 : c2; // ★NG: コンパイルエラー // error CS0173: Type of conditional expression cannot be determined // because there is no implicit conversion between `Child1' and `Child2' }
下記コードのように、共通の親クラス型へと明示キャストすれば意図通り動作する。
// OK: rはParent型 var r = b ? (Parent)c1 : (Parent)c2;
Standard ECMA-334 C# Language Specification(4th Ed.) 14.13 Conditional operatorより該当箇所を引用。
The second and third operands of the
?:operator control the type of the conditional expression. LetXandYbe the types of the second and third operands. Then,
- If
XandYare the same type, then this is the type of the conditional expression.- Otherwise, if an implicit conversion (§13.1) exists from
XtoY, but not fromYtoX, thenYis the type of the conditional expression.- Otherwise, if an implicit conversion (§13.1) exists from
YtoX, but not fromXtoY, thenXis the type of the conditional expression.- Otherwise, no expression type can be determined, and a compile-time error occurs.
関連URL