goofballLogic goofballLogic - 1 year ago 69
C# Question

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)
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();

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download