Apparently, you cannot use a null
for a key, even if your key is a nullable type.
This code:
var nullableBoolLabels = new System.Collect
There is no fundamental reason. HashSet allows null and a HashSet is simply a Dictionary where the key is the same type as the value. So, really, null keys should have been allowed but would be breaking to change it now so we're stuck with it.
Dictionaries can't accept null reference types for a variety of reasons, not least because they don't have a GetHashCode method.
A null value for nullable value type is meant to represent a null value – the semantics are meant to be as synonymous with a reference null as possible. It would be slightly odd if you could use null nullable value where you couldn't use null references just because of an implementation detail of nullable value types.
Either that or Dictionary has:
if (key == null)
and they never really thought about it.
Key value must to be unique, so null cannot be a valid key because null indicate no key.
That why .Net framework doesn't allow null value and throw an exception.
As far as why Nullable allowed, and not catches at compile time, I think the reason is because that where
clause that allow everyt T
except Nullable one is not possible (at least I don't know how to achieve that).
Dictionary keys can't be null in .NET, regardless of the type of the key (nullable or otherwise).
From MSDN: As long as an object is used as a key in the Dictionary<(Of <(TKey, TValue>)>), it must not change in any way that affects its hash value. Every key in a Dictionary<(Of <(TKey, TValue>)>) must be unique according to the dictionary's equality comparer. A key cannot be null reference (Nothing in Visual Basic), but a value can be, if the value type TValue is a reference type. (http://msdn.microsoft.com/en-us/library/xfhwa508.aspx)
Dictionairies (basic description)
A dictionary is the generic (typed) implementation of the Hashtable class, introduced in .NET framework 2.0.
A hashtable stores a value based on a key (more specificly a hash of the key).
Every object in .NET has the method GetHashCode
.
When you insert an key value pair into an hashtable, GetHashCode
is called on the key.
Think of it: you can't call the GetHashCode
method on null
.
So what about Nullable types?
The Nullable
class is simply a wrapper, to allow null values to be assigned to value types. Basically the wrapper consists of an HasValue
boolean that tells if it is null or not, and a Value
to contain the value of the value type.
Put it together and what do you get
.NET doesn't really care what you use as a key in a hashtable/dictionary.
But when you add a key value combination, it has to be able to generate a hash of the key.
It doesn't matter if your value is wrapped inside a Nullable
, null.GetHashCode is impossible.
The Indexer property and Add methods of the Dictionary will check for null, and throw an exception when it finds null.