Why does C # make this type 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 output by the compiler for whatami1is string.
The type output by the compiler for whatami2is dynamic.
The type output by the compiler for whatami3is bool.

Why is the second type not bool?

+6
source share
2 answers

To expand the PetSerAl comment explaining why it is considered dynamic, you can avoid having your call bool.Parsebe treated as dynamic by casting the value to a string:

var whatami2 = hasValue ? bool.Parse((string)value) : true;
+2
source

- () , - - :

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

, - - (, ) var ( whatami2), :

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

All Articles