Reputation: 8477
I have an immutable class whose only field is a bool[]
(size determined at runtime).
How can I compute a good hash code of this class? Generally I would just call GetHashCode()
on each field, and combine them with one of these operators: + | &
, but since the only possible hash codes are 0
for false
and 1
for true
, that's not really going to get me anywhere. My implementation needs to work with only bools
, and must work for an arbitrary-sized array.
(Probably doesn't matter much, but I'm coding in C#/.NET.)
Upvotes: 10
Views: 2395
Reputation: 241701
Assuming your bool[]
is named bools
:
unchecked {
int hash = 17;
for(int index = 0; index < bools.Length; index++) {
hash = hash * 23 + bools[index].GetHashCode();
}
return hash;
}
Upvotes: 10