I have a list of IPv4s as byte[]'s from page visits. To get a unique list, I want to add them to a HashSet. Using the following code puts duplicate entries into the HashSet, which I used to believe was impossible.
byte[] a = new byte[] {0,0,0,1};
byte[] b = new byte[] {0,0,0,1};
HashSet<byte[]> hashBytes = new HashSet<byte[]>();
hashBytes.Add(a);
hashBytes.Add(b);
I expect the hashset to only contain a, but it contains both a and b.
EDIT: As per a commenter I added in the additional code:
public class IPComparer : IEqualityComparer<byte[]>
{
public bool Equals(byte[] a, byte[] b)
{
//They are not an IP address
if (a.Length != 4 && b.Length != 4)
{
return false;
}
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}
public int GetHashCode(byte[] a)
{
uint b = 0;
for (int i = 0; i < a.Length; i++)
{
b = ((b << 23) | (b >> 9)) ^ a[i];
}
return unchecked((int)b);
}
I also made the HashSet with new HashSet(IPComparer) instead of the regular comparer. The results did not change.