2

Ok so I need a bit of help. I have a generic dictionary "cashdata". The keys of this dictionary are objects (Query objects, a class I have defined). Query objects have "Terms" field, which is a list of strings, and an "Operator" field, which is an enum (Either "All" or "Any").

cashdata.ContainsKey(a_query_object);

And have it yield true or false depending on if a_query_object and an object in the dictionary are identical in terms of their Terms and Operator. What is the best way to do this? A HashCode possibly? I would appreciate an example, thanks in advance.

EDIT: cashdata Dictionary is defined as such

Dictionary<Query,List<string> > cashData = new Dictionary<Query,List<string>>();
Wes Field
  • 3,291
  • 6
  • 23
  • 26
  • please show more code and or how you have defined this Generic Dictionary please. – MethodMan Jul 22 '13 at 21:35
  • 5
    Override `Equals` and `GetHashCode` on your custom object, put breakpoints in, and step through the code -- this will help you understand how `ContainsKey`, as well as other methods of the dictionary, works. – Austin Salonen Jul 22 '13 at 21:36
  • Be sure that the Terms and Operator of Query objects cannot change after they've been added to the Dictionary. If that does happen, you will not be able to find the object properly in the Dictionary. – hatchet - done with SOverflow Jul 22 '13 at 21:43
  • 1
    If you can't override `Equals` and `GetHashCode` on your custom object, provide an [IEqualityComparer](http://msdn.microsoft.com/en-us/library/ms132151.aspx) to the dictionary constructor. The MSDN topic has a good example. – Jim Mischel Jul 22 '13 at 21:45

1 Answers1

1

Make your object implement IEquatable Interface along with overriding Object.Equals and GetHashCode as mentioned in the remarks section in MSDN

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.

Mahmoud Darwish
  • 1,168
  • 1
  • 15
  • 28
  • Be careful with `IEquatable`. [Inheritance and IEquatable do not mix](http://blog.mischel.com/2013/01/05/inheritance-and-iequatable-do-not-mix/) – Jim Mischel Jul 23 '13 at 13:53
  • @JimMischel i am not sure what i made that was different than your code, but i tried the first test with the same code you have(simple copy & paste) and i had false returned 4 times, in both cases (with and without the symbols) – Mahmoud Darwish Jul 23 '13 at 15:19