Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this Dictionary<TKey, TValue> exception possible?

Given the following stack trace:

MESSAGE: Value cannot be null.Parameter name: key  
SOURCE: mscorlib  
TARGETSITE: Void ThrowArgumentNullException(System.ExceptionArgument)  
STACKTRACE:  
   at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)  
   at System.Collections.Generic.Dictionary'2.FindEntry(TKey key)  
   at System.Collections.Generic.Dictionary'2.get_Item(TKey key)  
   at MyCompany.MAF.Agent.ServiceContracts.ConvertUtils.Convert(Dictionary'2 from) in D:\Development\MAF\Agent\MyCompany.MAF.Agent\ServiceContracts\ConvertUtils.cs:line 11

I conclude that somehow the following block of code has retrieved a null from the input Dictionary's Keys collection. However, the input dictionary is an instance of Dictionary<string, string>. The implementation of Dictionary<string, string> makes that condition impossible. Upon adding an item with a null key, an exception is thrown.

internal static KeyValuePair<string, string>[] Convert(IDictionary<string, string> from)
{
    List<KeyValuePair<string, string>> ret = new List<KeyValuePair<string, string>>();
    foreach (string key in from.Keys)
        ret.Add(new KeyValuePair<string, string>(key, from[key]));
    return ret.ToArray();
}
like image 574
goofballLogic Avatar asked Feb 17 '10 18:02

goofballLogic


People also ask

Can a dictionary key be null?

Dictionaries can't have null keys.

How do you check if a key exists in a dictionary C#?

ContainsKey() Method. This method is used to check whether the Dictionary<TKey,TValue> contains the specified key or not. Syntax: public bool ContainsKey (TKey key);

Can we add duplicate keys in dictionary C#?

In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.

How does dictionary work in C#?

The Dictionary class in C# represents a generic data structure that can contain keys and values of data. Hence, you can store data of any type in a Dictionary instance.


1 Answers

I've had this problem happen frequently because I made the mistake of allowing multiple threads to access the same dictionary. Make sure that this is not the case, because Dictionary is not thread-safe.

(Incidentally, your method can be greatly simplified. Dictionary<K,V> is already an IEnumerable<KeyValuePair<K,V>>. You should be able to just do ToArray on one.

like image 165
Jacob Avatar answered Nov 01 '22 14:11

Jacob