Overriding GetHashCode in a mutable struct - What NOT to do?
Posted
by
Kyle Baran
on Programmers
See other posts from Programmers
or by Kyle Baran
Published on 2014-05-13T03:06:43Z
Indexed on
2014/06/03
21:39 UTC
Read the original article
Hit count: 575
I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct.
As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode()
(which Point overrides), this is a rather bad thing, since if an object's values change while its contained in a hashmap (ie, LINQ queries), it can become "lost".
However, I am making my own Point3D
struct, following the design of Point
as a guideline. Thus, it too is a mutable struct which overrides GetHashCode()
. The only difference is that mine exposes and int for X, Y, and Z values, but is fundamentally the same. The signatures are below:
public struct Point3D : IEquatable<Point3D>
{
public int X;
public int Y;
public int Z;
public static bool operator !=(Point3D a, Point3D b) { }
public static bool operator ==(Point3D a, Point3D b) { }
public Point3D Zero { get; }
public override int GetHashCode() { }
public override bool Equals(object obj) { }
public bool Equals(Point3D other) { }
public override string ToString() { }
}
I have tried to break my struct in the way they describe, namely by storing it in a List<Point3D>
, as well as changing the value via a method using ref
, but I did not encounter they behavior they warn about (maybe a pointer might allow me to break it?).
Am I being too cautious in my approach, or should I be okay to use it as is?
© Programmers or respective owner