Jon Skeet, if you're listening, this might be of interest to you, since it's related to your code puzzle here... http://codeblog.jonskeet.uk/2014/01/14/a-tale-of-two-puzzles/
Code
public class Test
{
public static void Main()
{
bool? x = (true) ? null : default(bool?);
bool? y = (true) ? x is bool? : default(bool?);
Console.WriteLine(x);
Console.WriteLine(y);
Console.Read();
}
}
Output
False
What puzzles me, is that I expected to see this...
True
bool? y = (true) ? x is bool? : default(bool?);
since : default(bool?) will never be hit, why is x is bool? returning false, when it IS bool? ?
The first statement obviously sets the value of x to null. The second statement checks to see if the value of x "is a" bool?.
The is operator does not care about the declared type of the variable. It looks at the actual type of the object that's being evaluated. Since x is set to null, the value that's passed to the is operator is null, meaning there is no object being referenced, and thus is bool? returns false.
From MSDN:
An
isexpression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With