RSS 2.0 Feed
RSS 2.0

Atom 1.0 Feed
Atom 1.0

  More on Nullable Value Types 


I posted about a week ago about the new nullable value types in C# 2.0. Since then the new C# Language Specification has been released - which now includes a section on nullable value types, so it has gained a bit of buzz in the blogsphere over the past week. Eric Gunnerson posted on the C# Team FAQ a little more related to nullable types and answers the question "Why don't nullable relational operators return 'bool?' instead of 'bool'?".

For example, take a look at the following:

int? x = 1;
int? y = 2;

// the type of 'x==y' results in a normal 'bool', not a 'bool?'
bool xy = (x == y);

Eric goes on to explain why. Since a comparison of a nullable type can yield a ternary result, true/false/null, and null is not equal to anything (comparing anything with null results in null) then the comparison can never succeed. The only way for such a comparison to succeed would be to use the nullable type's HasValue method, such as the following:

bool? b = null;
if (!b.HasValue) { }

This is not very natural syntax. A programmer would expect to use more normal syntax such as this:

bool? b = null;
if (b == null) { }

But as I mentioned before, this comparison could never succeed. Therefore, the design decision was made to force all relational operators return a normal binary bool. Makes sense to me ;-)


I wanted to clarify. It is because the C# design team wanted to allow a developer to use the more normal syntax of if (b == null) that the decision was made to have the relational operators return a normal bool resulting in only two possible results true/false - making the comparison above valid. However you still have the option to use the ?? operator to test for nullness and use alternate values instead.


Comments have been closed on this topic.



Also see my CRM Developer blog