Change a dynamic's type in a ternary conditional statement

前端 未结 2 2018
攒了一身酷
攒了一身酷 2021-01-29 02:47

In C#, the type dynamic allows you to change a variable\'s type at runtime, for example:

dynamic x = \"foo\";
x = 42;

Another exam

相关标签:
2条回答
  • 2021-01-29 03:20

    The type of the conditional operator is determined regardless of the surrounding expression. In other words it really doesn't matter what is before =, (true) ? "foo" : 42; is illegal.

    The solution is to cast the types of the operands instead:

    dynamic x = (true) ? (dynamic) "foo" : (dynamic)  42;
    

    You can cast just one of them if you wish.


    One other thing, the operator's name is "the conditional operator", not "ternary operator", even if it is the only ternary operator in C#.

    0 讨论(0)
  • 2021-01-29 03:26

    The specification has this to say about how it uses the operands to determine the type of a ternary expression:

    The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

    •If x has type X and y has type Y then,

    o If X and Y are the same type, then this is the type of the conditional expression.

    o Otherwise, if an implicit conversion (§11.2) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

    o Otherwise, if an implicit enumeration conversion (§11.2.4) exists from X to Y, then Y is the type of the conditional expression.

    o Otherwise, if an implicit enumeration conversion (§11.2.4) exists from Y to X, then X is the type of the conditional expression.

    o Otherwise, if an implicit conversion (§11.2) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

    o Otherwise, no expression type can be determined, and a compile-time error occurs.

    Obviously none of these (excluding the final statement) are true for string and int, so you get the compile time error.

    Essentially, the type of the variable you're assigning the result of your ternary to doesn't have an impact on the resulting type of the ternary expression. If you want to return dynamic, you'll need to cast one of the operands to dynamic directly, like so:

    dynamic x = (true) ? (dynamic) "foo" : 42;
    
    0 讨论(0)
提交回复
热议问题