How it is possible that you get a KeyNotFoundException when calling a Dictionary?
Given the signature of the method I'm calling:
IDictionary<string, string> RequestParams { get; }
Given the call that I'm making:

Given that I am returning a Dictionary<string, string> as follows:
public IDictionary<string, string> RequestParams
{
get
{
NameValueCollection nvc = HttpContext.Request.Params;
#region Collect the Request Params
Dictionary<string, string> dict = new Dictionary<string, string>();
nvc.AllKeys.ForEach(s => dict[s] = nvc[s]);
#endregion
#region Collect the Route Data Present in the Url
RouteData.Values.ForEach(pair =>
{
string param = (pair.Value ?? "").ToString();
if (!String.IsNullOrEmpty(param) && Uri.AbsolutePath.Contains(param))
dict[pair.Key] = param;
});
#endregion
return dict;
}
}
And I've actually inspected that it indeed returns an instantiated and populated Dictionary<string, string>
Notice, not Dictionary, but IDictionary. The underlying implementation can do whatever it wants to do, even shut down your computer.
The Dictionary does not throw any exceptions (except key null exception) when using ContainsKey.
It's possible that the specific implementation of IDictionary you're using, throws KeyNotFoundException, but that would still be weird - although, I've seen a lot weirder things, so don't panic :-)!
Possible causes:
Dictionary, make sure you have namespace System.Collections.Generic
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