Matthew Layton
Matthew Layton

Reputation: 42380

C# code puzzle returns a puzzling result

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

Upvotes: 3

Views: 155

Answers (1)

D Stanley
D Stanley

Reputation: 152624

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.

Upvotes: 10

Related Questions