vendredi 23 août 2019

Change a dynamic's type in a ternary conditional statement

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

dynamic x = "foo";
x = 42;

Another example:

dynamic x;
if (true)
    x = "foo";
else
    x = 42;

However, when using the shorthand "?:" ternary conditional statement,

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

will not compile:

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

Why is that so?

Aucun commentaire:

Enregistrer un commentaire