Question

In the code below, I was wondering why XOR (^) is being used to combine the hascodes of the constituent members of the composition (this is source from MonoCross 1.3)?

  1. Is the bitwise XOR of an MXViewPerspective object's Perspective and ModelType member's used to uniquely identify the instance ?

  2. If so, is there a name for this property of the XOR operation (how XOR-ing two values (ie, hashcodes) guarantees uniqueness) ?


public class MXViewPerspective : IComparable
{
    public MXViewPerspective(Type modelType, string perspective)
    {
        this.Perspective = perspective;
        this.ModelType = modelType;
    }
    public string Perspective { get; set; }
    public Type ModelType { get; set; }

    public int CompareTo(object obj)
    {
        MXViewPerspective p =(MXViewPerspective)obj;
        return this.GetHashCode() == p.GetHashCode() ? 0 : -1;
    }
    public static bool operator ==(MXViewPerspective a, MXViewPerspective b)
    {
        return a.CompareTo(b) == 0;
    }
    public static bool operator !=(MXViewPerspective a, MXViewPerspective b)
    {
        return a.CompareTo(b) != 0;
    }
    public override bool Equals(object obj)
    {
        return this == (MXViewPerspective)obj;
    }
    public override int GetHashCode()
    {
        return this.ModelType.GetHashCode() ^ this.Perspective.GetHashCode();
    }

    public override string ToString()
    {
        return string.Format("Model \"{0}\" with perspective  \"{1}\"", ModelType, Perspective);
    }
}

Thank you.

Was it helpful?

Solution

xor'ing hashcodes doesn't guarantee uniqueness, but is usually used to improve the distribution over a table without complicating the hashing.

You want to make 2 different values map to different hash keys if they differ in any of the fields (i.e. - same ModelType, but different Perspective, or vice versa). So you need to incorporate both values into your hash key. You could have used + for example, or shift and concatenate them (the latter would be better in fact, as it would guarantee uniqueness, but also extend the key length which might complicate hashing).

xor won't guarantee this uniqueness since if you flip the same bit in ModelType and Perspective, you'd get the same hash key, for example 5 ^ 7 = 1 ^ 3 = 2, but it's usually good enough. Eventually it all depends on the ranges and distributions of the values you provide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top