Why does C# infer this type as dynamic?

Viewed 164

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?

2 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;

Casting is our assertion (to the compiler) that an object really is something else - for example:

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

Finally, parsing is interpreting a value from a form with no intrinsic relationship - i.e. there is no direct relationship between a dynamic ( i.e. value) and var (i.e. whatami2), but we can parse:

var whatami2 = hasValue ? bool.Parse(value) : true;
Related