Jani Hyytiäinen
Jani Hyytiäinen

Reputation: 5407

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

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>

Upvotes: 7

Views: 1285

Answers (2)

Erti-Chris Eelmaa
Erti-Chris Eelmaa

Reputation: 26298

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 ^_^

Upvotes: 7

user1852503
user1852503

Reputation: 5607

It can't throw that exception.

look at the using statements of the file with the getter. do you see:

  using System.Collections.Generic;

or is it:

  using MyAmazingLib.BetterThanMS.Collections;

Upvotes: 1

Related Questions