Apparently, you cannot use a null
for a key, even if your key is a nullable type.
This code:
var nullableBoolLabels = new System.Collections.Generic.Dictionary<bool?, string> { { true, "Yes" }, { false, "No" }, { null, "(n/a)" } };
...results in this exception:
Value cannot be null. Parameter name: key
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
[ArgumentNullException: Value cannot be null. Parameter name: key]
System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument) +44
System.Collections.Generic.Dictionary'2.Insert(TKey key, TValue value, Boolean add) +40
System.Collections.Generic.Dictionary'2.Add(TKey key, TValue value) +13
Why would the .NET framework allow a nullable type for a key, but not allow a null value?
Dictionary will hash the key supplie to get the index , in case of null , hash function can not return a valid value that's why it does not support null in key.
null cannot be used as key in a dictionary, because you need a hashcode of the key. And the key must be unique. So you could replace null with some magic value, but it still would crash if you have multiple rows where the key is null .
In the same way, cities is a Dictionary<string, string> type dictionary, so it can store string keys and string values. Dictionary cannot include duplicate or null keys, whereas values can be duplicated or null.
C# has two different categories of types: value types and reference types. Amongst other, more important distinctions, value types, such as bool or int, cannot contain null values.
It would tell you the same thing if you had a Dictionary<SomeType, string>
, SomeType
being a reference type, and you tried to pass null
as the key, it is not something affecting only nullable type like bool?
. You can use any type as the key, nullable or not.
It all comes down to the fact that you can't really compare nulls
. I assume the logic behind not being able to put null
in the key, a property that is designed to be compared with other objects is that it makes it incoherent to compare null
references.
If you want a reason from the specs, it boils down to a "A key cannot be a null reference " on MSDN.
If you want an exemple of a possible workaround, you can try something similar to Need an IDictionary implementation that will allow a null key
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With