Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# code puzzle returns a puzzling result

Tags:

c#

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? ?

like image 489
Matthew Layton Avatar asked Dec 28 '25 14:12

Matthew Layton


1 Answers

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 is expression 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.

like image 157
D Stanley Avatar answered Dec 31 '25 04:12

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!