0

Is it possible to achive the following behaviour from a dictionary in a convenient way:

Dictionary<MyObject, double> d = new Dictionary<MyObject, double>
MyObject foo = new MyObject("foo");
d[foo] = 1.0;

Console.Write(d[new MyObject("foo")]) ---> 1.0

The example is simplified, I am using a slightly more complex Object as key.

Edit replaced String with MyObject

SverkerSbrg
  • 503
  • 1
  • 9
  • 23

1 Answers1

2

Yes, it is possible, as long as the corresponding Equals() method of your key returns true, and GetHashCode() returns the same integer value for what you call different but identical instances.

In your example the result is 1.0 because String.Equals compares contents of the strings, not references (although, to be precise, references in your example will most probably be the same as well, because the compiler usually pools identical strings). EDIT: this paragraph applied to the original question, where the OP used string as the key.

If you use custom class for keys, just override its Equals method to achieve desired behavior. Don't forget to override GetHashCode() as well for efficient dictionary lookup, see this for reasoning: Why is it important to override GetHashCode when Equals method is overridden?

Community
  • 1
  • 1
Denis Yarkovoy
  • 1,277
  • 8
  • 16
  • Thank you, I must have made an error in my GetHashCode implementation. I'll do some testing :) – SverkerSbrg Jun 18 '15 at 09:37
  • Always override `Equals` **and** `GetHashCode`. You can also implement an `IEquatable` or an `IEqualityComparer`. The former works implicitly, the latter by using [this dictionary constructor](https://msdn.microsoft.com/en-us/library/ms132072(v=vs.110).aspx). – Tim Schmelter Jun 18 '15 at 09:43
  • @Tim Schmelter, good point, re-phrased my answer to include your recommendation – Denis Yarkovoy Jun 18 '15 at 09:45