Skip to content

Instantly share code, notes, and snippets.

@geekley
Last active August 14, 2018 17:45
Show Gist options
  • Save geekley/3e0d3acab5642a7603e7bf232ce26582 to your computer and use it in GitHub Desktop.
Save geekley/3e0d3acab5642a7603e7bf232ce26582 to your computer and use it in GitHub Desktop.
A good implementation of GetHashCode in C#
V val; // struct
T obj; // class
V? nlv; // Nullable
X unk; // not known if class or struct
public override int GetHashCode() {
int h = 23;
unchecked {
h = (h << 5) - h + val.GetHashCode();
h = (h << 5) - h + (obj != null ? obj.GetHashCode() : 0);
h = (h << 5) - h + (nlv != null ? nlv.GetHashCode() : int.MinValue);
h = (h << 5) - h + (unk is System.ValueType || (object)unk != null ? unk.GetHashCode() : 0);
}
return h;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment