Reputation: 13125
If I want to use objects of this class as keys in a Dictionary, what do I need to do? (10.0, 20.0) shouldn't exist as a key twice.
public class IntPoint
{
public Int64 X { get; set; }
public Int64 Y { get; set; }
public IntPoint(Int64 X, Int64 Y)
{
this.X = X; this.Y = Y;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
}
EDIT
public static Dictionary<IntPoint, List<int>> GetPolygonDuplicateIndixes(Polygon p)
{
Dictionary<IntPoint, List<int>> d = new Dictionary<IntPoint, List<int>>();
int i = 0;
foreach(IntPoint point in p)
{
if(!d.ContainsKey(point))
{
d[point] = new List<int>();
}
d[point].Add(i);
i++;
}
...
I'm getting duplicates in d. Why? 22002, 1501 occurs twice in p.
Upvotes: 3
Views: 401
Reputation: 4669
If you look at the Dictionary documentation, you'll see that if the keys implement IEquatable, that equality implementation will be used instead.
Upvotes: 6
Reputation: 3358
Your GetHashCode can look like:
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
But you still need to override Equals
and implement IEquatable
interface.
You may also use Tuple<Int64, Int64>
instead of your own IntPoint
class (if you're on .NET 4.0).
Upvotes: 2
Reputation: 8880
The following link from MSDN recommends using combining X and Y using an XOR operation
http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx#Y1500
public override int GetHashCode() {
return X ^ Y;
}
The thing to remember is that
Upvotes: 2