tags:

views:

10409

answers:

7

In C# are the nullable primitive types (i.e. bool?) just aliases for their corresponding Nullable<T> type or is there a difference between the two?

+4  A: 

A Nullable<T> is a structure consisting of a T and a bit flag indicating whether or not the T is valid. A Nullable<bool> has three possible values: true, false and null.

Edit: Ah, I missed the fact that the question mark after "bool" was actually part of the type name and not an indicator that you were asking a question :). The answer to your question, then, is "yes, the C# bool? is just an alias for Nullable<bool>".

Curt Hagenlocher
This didn't answer the question.
spoulson
Yes, I realized that after seeing your answer. Thanks!
Curt Hagenlocher
+2  A: 

Null primitives are just regular primitives wrapped in Nullable. Any appearances to the contrary are just the compiler and syntactical sugar.

Will
A: 

A bool is a value type, therefore it can't contain a NULL value. If you wrap any value type with Nullable<>, it will give it that ability. Moreover, access methods to the value change by additional properties HasValue and Value.

But to the question: Nullable<bool> and bool? are aliases.

spoulson
Why is someone systematically downvoting correct answers?
Konrad Rudolph
Even though this comment was from way back it's possible that they felt this answer duplicated other answers so they DV'd?
Chris Marisic
Apparently I'm not the fastest gun in the west. All the top answers are within a few minutes.
spoulson
+14  A: 

There is no difference between bool? b = null and Nullable<bool> b = null. The ? is just C# compiler syntax sugar.

samjudson
+2  A: 

To access the value of the bool? you need to do the following:

bool? myValue = true;
bool hasValue = false;

if (myValue.HasValue && myValue.Value)
{
  hasValue = true;
}

Note you can't just do:

if (myValue)
{
  hasValue = true;
}
Mark Ingram
hmm, not sure whether or not to up-vote this as it doesnt answer the question but it's useful and succinct nonetheless! ;-)
rohancragg
Well, according to Joel you should up-vote if you find it useful - not neccessarily if it's the answer. But then I would say that ;)
Mark Ingram
+15  A: 

If you look at the IL using ILDasm, you'll find that they both compile down to Nullable<>.

Steve Morgan
A: 

No there is no difference. In summary:

System.Boolean -> valid values : true, false

bool -> alias for System.Boolean

Nullable<bool> -> valid values : true, false, null

bool? -> alias for Nullable<bool>

Hope this helps.

morechilli