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();
}
Dictionaries can't have null keys.
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);
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.
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.
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.
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