Change a dynamic's type in a ternary conditional statement

前端 未结 2 2042
攒了一身酷
攒了一身酷 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#.

提交回复
热议问题