I use the “bool” type for variables as I was used to in C++, and I try to put the values of functions or properties I expect to be boolean into my variable. However I often encounter cases where the result type is “bool?” and not “bool” and the implicit casting fails.
What is the difference between the two and when is each used? Also, should I use “bool?” as the type for my variable? Is this the best practice?
The
?symbol after a type is only a shortcut to the Nullable type,bool?is equivalent toNullable<bool>.boolis a value type, this means that it cannot benull, so the Nullable type basically allows you to wrap value types, and being able to assignnullto them.bool?can contain three different values:true,falseandnull.Also, there are no short-circuiting operators (&& ||) defined for
bool?Only the logical AND, inclusive OR, operators are defined and they behave like this:
The Nullable type is basically a generic struct, that has the following public properties:
The
HasValueproperty indicates whether the current object has a value, and theValueproperty will get the current value of the object, or if HasValue is false, it will throw an InvalidOperationException.Now you must be wondering something, Nullable is a struct, a value type that cannot be null, so why the following statement is valid?
That example will compile into this:
A call to initobj, which initializes each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.
That’s it, what’s happening here is the default struct initialization.
Is equivalent to: