Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Dictionary.ContainsKey throw ArgumentNullException? [closed]

The documentation states that bool Dictionary<TKey, TValue>.ContainsKey(TKey key) throws an exception in case a null key is passed. Could anyone give a reason for that? Wouldn't it be more practical if it just returned false?

like image 211
Marcin Kaczmarek Avatar asked Dec 06 '13 15:12

Marcin Kaczmarek


2 Answers

If ContainsKey(null) returned false it would give the misleading impression that null keys are allowed..

like image 181
stuartd Avatar answered Oct 16 '22 04:10

stuartd


This is how it is implemented: (Source)

public bool ContainsKey(TKey key) {
    return FindEntry(key) >= 0;
}

And the method FindEntry as:

private int FindEntry(TKey key) {
    if( key == null) {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }

    if (buckets != null) {
        int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
        for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
            if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
        }
    }
    return -1;
}

Since having a null value as key in dictionary is not allowed.

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add(null, 10);

The above would produce an exception:

Value cannot be null. Parameter name: key

For your question:

Wouldn't it be more practical if it just returned false?

Someone from Microsoft could probably reply that. But IMO, since adding a null value for key is not allowed there is no point in checking for null key in ContainsKey

like image 28
Habib Avatar answered Oct 16 '22 05:10

Habib