1

I'm at a loss. I have a Dictionary object with String keys. The objects are of a custom type I have. This example throws an InvalidCastException:

MyObject temp;
if(Dict.TryGetValue("abc", out temp)) //exception

If I instead use "ContainsKey", I still get an InvalidCastException:

if(Dict.ContainsKey("abc")) //exception

In both cases, if I put a watch on Dict["abc"], I get the value that I want from the Dictionary. The Exception details provide no extra information.

I tried putting together a small code sample that replicates this situation, but my code samples work perfectly. I don't know how to provide a code sample for this problem.

Why would I get an InvalidCastException when checking for the existence of a key in a Dictionary? Why does ContainsKey even need to do any casting in its implementation? How do I fix this?

user1214135
  • 625
  • 2
  • 11
  • 22
  • 2
    So you can't reproduce it, and there's *no* information in the exception? Like, a stack trace perhaps? It's not clear how anyone is meant to be able to help. – Jon Skeet Feb 24 '12 at 17:02
  • can you post the declaration of your dictionary? ContainsKey only throws ArgumentNullException and not an InvalidCastException, so it something you are doing before or has to do with the declaration of your dictionary. – Jetti Feb 24 '12 at 17:03
  • 1
    Could you add the declaration of Dict? – Joachim Isaksson Feb 24 '12 at 17:04
  • 2
    We all want to see your Dict. – demoncodemonkey Feb 24 '12 at 17:05
  • Dictionary _Key2Trades = new Dictionary(); – user1214135 Feb 24 '12 at 17:06
  • The thing is that I tried making a trivial example of this, but my trivial example worked fine. What are some things I should look for when getting this exception while calling "ContainsKey"? – user1214135 Feb 24 '12 at 17:07
  • Look at the inner exception of the InvalidCastException and post it here. – demoncodemonkey Feb 24 '12 at 17:08
  • @user1214135: Could you post the full stack trace? – Jon Skeet Feb 24 '12 at 17:10
  • The inner exception is null. The message is "Specified cast is not valid". – user1214135 Feb 24 '12 at 17:15
  • Ok I figured it out. Visual Studio 2010 was showing that the exception was being thrown at my TryGetValue(...) call, but the real problem was a few lines above that. I was casting a DbNull.Value to a decimal? without realizing it. I don't know why Visual Studio highlighted the wrong line, but it doesn't matter now. I have the Configuration set to DEBUG. Thanks for your help everyone. – user1214135 Feb 24 '12 at 17:18

1 Answers1

0

Well, I can come up with a way of reproducing it, but whether or not it's what's going wrong here is impossible to tell:

using System;
using System.Collections.Generic;

public class Test
{
    static void Main()
    {
        var dictionary = new Dictionary<string, string>(new BadComparer());
        string temp;
        dictionary["bad"] = "oops"; // Fine...
        dictionary.TryGetValue("bad", out temp); // Bang!
    }    
}

class BadComparer : IEqualityComparer<string>
{
    public int GetHashCode(string x)
    {
        return x.GetHashCode();
    }

    public bool Equals(string x, string y)
    {
        // Bang!
        ((BadComparer) (object) x).ToString();
        return x.Equals(y);
    }
}

Note that this does give relevant information in the exception:

Unhandled Exception: System.InvalidCastException: Unable to cast object of type
'System.String' to type 'BadComparer'.
   at BadComparer.Equals(String x, String y)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at Test.Main()
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194