LMS
LMS

Reputation: 4217

Two byte arrays of identical value aren't equal

While writing a program, I recently came across an odd problem. Two byte arrays of eight values, with identical values in each, are reported as being inequal when using the == operator, and the values for GetHashCode() are different too.

byte[] id = new byte[8] {
    0x00, 0x00, 0x00, 0x00,
    0xF8, 0x00, 0x00, 0x00
};
byte[] od = new byte[8] { 
    0x00, 0x00, 0x00, 0x00,
    0xF8, 0x00, 0x00, 0x00 
};

Console.WriteLine(id == od);
Console.WriteLine(id.GetHashCode());
Console.WriteLine(od.GetHashCode());
Console.ReadLine();

The output of this program to the console is as follows:

False
45653674
41149443

Can anyone offer some input as to why these byte arrays aren't considered equal?

Upvotes: 1

Views: 341

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503110

Can anyone offer some input as to why these byte arrays aren't considered equal?

It's very simple: array types don't override Equals or GetHashCode (or indeed ToString) - so you get the implementation from System.Object. The Equals implementation in System.Object just compares reference identity, and GetHashCode attempts to give a unique hash code for each object, as far as possible. You have two separate array objects, so they're unequal (the references to the objects are different) and their hash codes are unlikely to be equal either.

Array types could override these methods, but they don't. You could write your own implementation of IEqualityComparer<T> which did this though. Mind you, using an array as a hash table key would usually be a bad idea anyway, as arrays are always mutable. You'd have to be really sure that nothing would ever mutate the array, which would change the hash code.

Note that the standard collections don't override these methods either - things like List<T> etc.

In my experience, the most common use for comparing arrays for equality is in unit tests - and typically unit test frameworks have methods to do this for you (e.g. in a CollectionAsserts class). Or LINQ provides Enumerable.SequenceEqual, as mentioned in other answers.

If you could tell us more about what you're trying to do, we can help you more.

Upvotes: 6

oleksii
oleksii

Reputation: 35925

This happens because id and od point to different objects.

You can use Enumerable class to compare the content of the array

Enumerable.SequenceEqual(id, od);

Upvotes: 0

chtenb
chtenb

Reputation: 16204

That is because id and od are two seperate arrays, with different pointers. If you want to know if their entries are the same, you should check the equality per value.

Upvotes: 5

Related Questions