5vighq
Last Updated: February 25, 2016
·
971
· keboo

Nullable gotcha

A small brain teaser using Nullable<bool>

Below is some code that was run through the VS immediate window.

new Nullable<bool>() is bool
false
new Nullable<bool>(false) is bool
true
new Nullable<bool>(false) is Nullable<bool>
true
new Nullable<bool>() is Nullable<bool>
false

This is because of the way the 'is' operator is defined. From the documentation "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." Since the default value of any nullable type is null, checking 'is' on a nullable object that does not contain a value always returns false.

Source: http://dotnetgeek.tumblr.com/post/11303229042/c-nullable-gotcha

Say Thanks
Respond