How does a ContainsKey (string key) throw a KeyNotFoundException in the <string, string> dictionary?

How is it possible that you get a KeyNotFoundException when you call the Dictionary?

Given the signature of the method I'm calling:

 IDictionary<string, string> RequestParams { get; } 

Given the call I'm making:

enter image description here

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 really checked that it really returns an instance and a filled Dictionary<string, string>

+7
dictionary c #
source share
2 answers

Note that not Dictionary , but IDictionary . The core implementation can do whatever it wants, even turn off the computer.

Dictionary does not use any exceptions (except for the null key exception) when using ContainsKey .

It is possible that the specific IDictionary implementation that you are using throws a KeyNotFoundException , but it will still be weird - though, I saw a lot of strange things, so don't panic :-)!

Possible reasons:

  • Your getter throws exceptions through other getters - use StackTrace to find out the origin.
  • You are using the wrong Dictionary , make sure you have the System.Collections.Generic namespace
  • Perhaps you are using the old code - it happened to me, very painful. Even debugging symbols can work. Just make some changes: comment on something obvious and see if it has any effect. If you comment out line 64 and get a KeyNotFoundException, you know something ... is not good ^ _ ^
+7
source share

He cannot throw this exception.

look at the used getter file operators. you see:

  using System.Collections.Generic; 

or that:

  using MyAmazingLib.BetterThanMS.Collections; 
+1
source share

All Articles