Why is it not possible to use the is operator to discern between bool and Nullable<bool>?

The reason bool and Nullable<bool> behave the same when passed to your method is because whenever you box a Nullable<T> it doesn't actually box the nullable value, instead it unwraps the value of the nullable and boxes that. If the nullable value is null then you end up with just null, rather than a boxed Nullable<T> where HasValue is false.

If you box a non-null value, it'll just box the Value of the Nullable<T>. So from the perspective of WhatIsIt, the first two calls are literally indistinguishable, because the exact same value is being passed in.

That just leaves the question of why both is checks return true, even though what's passed in, in both cases, is a boxed boolean, and not a Nullable<T>. That's answered by the C# language specs, section 7.10.10:

If T is a nullable type, the result is true if D is the underlying type of T.

In this case this is considering E is T and D is defined earlier as a computed value of E where:

If the type of E is a nullable type, D is the underlying type of that nullable type.

This means that the is operator is specifically defined as treating nullable types as being equivalent to their underlying types, regardless of how you mix and match the actual value being checked and the type you're checking with nullable values and that nullable's underlying type.


The value false can safely be converted to both bool and bool? because there´s an implicit cast-operator between them.

null on the other hand can´t be converted to bool, which is why null is bool returns false.

The is operator does not (and can´t) care about how you declared the variable - if at all. It just indicates the type of the value provided at runtime. You could have also written this:

WhatIsIt(false)

How would you expect the method to behave here? It simply tries to convert the value to both types - which it can - and thus returns true for both.

Why it does not work this way for other generics is simply because there´s no implicit conversion between the most generic types and their type-argument. Thus the following does not work:

string myString = new List<string>();

Nullable<T> class has implicit and explicit operators implemented which are used in such cases out of the box, take a look at documentation

Here is the excerpt from source code:

[System.Runtime.Versioning.NonVersionable]
public static implicit operator Nullable<T>(T value) {
    return new Nullable<T>(value);
}

[System.Runtime.Versioning.NonVersionable]
public static explicit operator T(Nullable<T> value) {
    return value.Value;
}

Tags:

C#

Types

Boxing