C # use class object as key in dictionary

I have a class that looks like this.

public class Point : IEquatable<Point> { public int _xValue {get;set;} public double _yValue {get;set;} public Point(int x, double y) { _xValue = x; _yValue = y; } public override bool Equals(object obj) { return Equals(obj as Point); } public bool Equals(Point obj) { return obj != null && obj._xValue == this._xValue && obj._yValue == this._yValue; } } 

I need to implement the GetHashCode function so that I can use it as a dictionary key. But I do not understand that the GetHashCode function should return in this situation. Can anybody help me?

+6
c #
source share
5 answers

It should return an integer, preferably unique to each individual instance of the object. A hash value is basically a single number created from the contents of an object used to uniquely identify that object. Rule number one is that if two of these points are evaluated equal to each other, the hash value must be the same for both of them.

A more detailed description is available on MSDN.

+4
source share

The GetHashCode function must return an integer that uniquely identifies one instance of the object from another in order to avoid collisions when it is used as a key in a dictionary.

You should be able to reliably reproduce the hash code, so try to avoid using random values ​​or date values ​​as seeds for the hash code.

+2
source share

You can do _xValue ^ _yValue.GetHashCode()

+1
source share

There are several basic rules for this:

  • Bool: if true returns 0, otherwise returns 1
  • Byte, char, short or int: return a value of type
  • Long: return (int) (f ^ f (β†’> 32))
  • Float: return Convert.ToInt32 type values
  • Object: returns the value generated by calling object.GetHashCode ()
  • Array: Iterate the entire array and process each element separately

so in your case you have x = int and y = double, if you follow these rules, you will find a solution.

return x ^ y.GetHashCode ();

You can always add some fantastic math algorithms, but be careful with numerical collisions.

+1
source share

In your case, you can do something like:

return x ^ y;

0
source share

All Articles