Alex Rivera | Logout

Custom Class used as key in Dictionary but key not found

Asked 2009-10-27T18:27:41.223
9

I have a class, show below, which is used as a key in a Dictionary<ValuesAandB, string> I'm having issues when trying to find any key within this dictionary, it never finds it at all. As you can see, I have overridden Equals and GetHashCode.

To look for the key I'm using

ValuesAandB key = new ValuesAandB(A,B);
if (DictionaryName.ContainsKey(key)) {
   ...
}

Is there anything else that I'm missing? Can anyone point out what I'm doing wrong?

private class ValuesAandB {
   public string valueA;
   public string valueB;

   // Constructor
   public ValuesAandB (string valueAIn, string valueBIn) {
     valueA = valueAIn;
     valueB = ValueBIn;
   }

   public class EqualityComparer : IEqualityComparer<ValuesAandB> {
      public bool Equals(ValuesAandB x, ValuesAandB y) {
         return ((x.valueA.Equals(y.valueA)) && (x.valueB.Equals(y.valueB)));
      }
      public int GetHashCode(ValuesAandB x) {
         return x.valueA.GetHashCode() ^ x.valueB.GetHashCode();
      }
   }
}

And before anyone asks, yes the values are in the Dictionary!

Edit
Report

1 Answer

1

I had this problem, turns out the dictionary was comparing referances for my key, not the values in the object.

I was using a custom Point class as keys. I overrode the ToString() and the GetHashCode() methods and viola, key lookup worked fine.

answered 2009-10-27T18:38:44.010

Your Answer