I am trying to make a Dictionary in C# that uses a boolean array for its keys.
Dictionary<bool[], string>
The bool array has fixed length of 1000, and all are the same length. I’m having trouble with the hashcode and the common method of an ‘exclusive or’ doesn’t make as much sense because of the length of the array.
Similar questions on StackOverflow are addressed with the ‘exclusive or’ in the GetHashCode method. I don’t think that works in this context. I would like to use it as:
Dictionary<bool[], string> myDict =
new Dictionary<bool[], string>(EqualityComparer);
where EquaityComparer does something like:
public class EqualityComparer : IEqualityComparer<bool[]>
{
public bool Equals(bool[] x, bool[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(bool[] x)
{
// this part doesn't work correctly
int hc = x.GetHashCode();
return hc;
}
}
Of course all of the usual concerns about the bool array being mutable and the size of any derived key being relevant to performance apply here…though I don’t have a solution.
Both your
EqualsandHashCodeare incorrect.Presumably you wish to use
SequenceEqualto compare the arrays for equality, or else a simple for loop.To calculate a hashcode you can use any of the standard methods. It is very important that if two items compare equal then they must have the same hash.
Example
Related