Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# infer this type as dynamic?

I have the following code.

public static void GuessTheType()
{
    dynamic hasValue = true;
    dynamic value = "true";

    var whatami1 = hasValue ? (string)value : null;
    var whatami2 = hasValue ? bool.Parse(value) : true;
    var whatami3 = hasValue ? (bool)bool.Parse(value) : true;
}

The type inferred by the compiler for whatami1 is string.
The type inferred by the compiler for whatami2 is dynamic.
The type inferred by the compiler for whatami3 is bool.

Why is the second type not bool?

like image 870
Cameron MacFarland Avatar asked Nov 16 '17 02:11

Cameron MacFarland


1 Answers

To expand on PetSerAl's comment, which explains why it's treated as dynamic, you can avoid having your call to bool.Parse treated as dynamic by casting the value to a string:

var whatami2 = hasValue ? bool.Parse((string)value) : true;
like image 191
Richard Szalay Avatar answered Oct 21 '22 23:10

Richard Szalay