Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can ContainsKey(string key) throw a KeyNotFoundException on a Dictionary<string, string>?

Tags:

c#

dictionary

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:

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've actually inspected that it indeed returns an instantiated and populated Dictionary<string, string>

like image 209
Jani Hyytiäinen Avatar asked Dec 19 '14 18:12

Jani Hyytiäinen


Video Answer


1 Answers

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:

  • Your getter is throwing exceptions through another getters - use StackTrace to find out the origin.
  • You are using wrong Dictionary, make sure you have namespace System.Collections.Generic
  • You might be running old code - this has happened to me, very painful. Even the debugging symbols might work. Just do some modifications: comment out something obvious, and see if it has any impact. If you comment out line 64 and you get KeyNotFoundException, you know something is... not good ^_^
like image 170
Erti-Chris Eelmaa Avatar answered Oct 17 '22 06:10

Erti-Chris Eelmaa