C# Hash Code for triangle class I have a custom class to handle some triangle calculations that I am doing. For the most part I am happy with it, however, there is one aspect that I don't really trust. That is my implementation of HashCode.

Some quick information about my triangle- it has 3 Vector2 structs that represent points of two floats. This is an inbuilt class with the Unity engine but the simple version of it is that it is a struct with two floats and a couple math functions.

public class Triangle2D {
    public Vector2 point1;
    public Vector2 point2;
    public Vector2 point3;

    //... Some other methods that don't matter

    public override int GetHashCode() {
        var hashCode = -305700999;
        hashCode = hashCode * -1521134295 + (EqualityComparer&lt;Vector2&gt;.Default.GetHashCode (point1)
            + EqualityComparer&lt;Vector2&gt;.Default.GetHashCode (point2)
            + EqualityComparer&lt;Vector2&gt;.Default.GetHashCode (point3));
        return hashCode;
    }
}


The specific thing about this class that is special is that, it shouldn't matter what order points 1, 2 and 3 are in. If the points are shared, then the Triangle2D objects are the same. My equals function reflects that, but I worry that my hashCode function is not specific enough. Due to the additive nature of things, I suspect there could be a lot of collisions.

Is there some way that I could make the hashCode function have less collisions? Is it good enough as it is?

I use this object in a lot of hashSets to prevent duplicate triangles from getting listed.
Hash code


  it shouldn't matter what order points 1, 2 and 3 are in


There is a way to ensure that: Sorting. Sort your points locally within your hashcode method, first by their x value, then by their y value.



The algorithm for the hashcode could be this one, as also commented above by radarbob. I will leave it for you to adapt it to your own class.

General

Your class has public fields. It is better to make these private and grant public access to them (if needed) via properties. In this case, for something like a triangle, making it a struct instead of a class might be also suitable.



The following piece of code does not make much sense:

var hashCode = -305700999;
hashCode = hashCode * -1521134295 + [...]


I already added the link to a good implementation of the hash code method above, so I won't go into detail about the algorithm. But what you are doing in the above two lines before the addition is just calculating what could simply be a constant. The compiler will probably even precompute the -305700999 * -1521134295 part. Multiplying the hash code with a prime number (like 23 or 31) should happen before every addition of another value.