25

I have two byte arrays with the exact same content. I tried:

if (bytearray1 == bytearray2) {...} else {...}

and

if (Array.Equals(bytearray1, bytearray2)) {....} else {...}

All time it goes to the else! I don't know why! I checked both arrays manually several times!!!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael
  • 747
  • 2
  • 10
  • 22

4 Answers4

73

Try using the SequenceEqual extension method. For example:

byte[] a1 = new byte[] { 1, 2, 3 };
byte[] a2 = new byte[] { 1, 2, 3 };
bool areEqual = a1.SequenceEqual(a2); // true
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
12

The == operator compares by reference; those are two different instances.

Array.Equals is really Object.Equals, which calls the instances Equals method.
Since arrays do not override Equals(), this too compares by reference.

Instead, you should call the LINQ SequenceEqual() method.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
8

Both the == operator and the Equals method will test reference equality. Since you have two separate arrays, they will never be equal.

Since you want to test that both arrays have the same content in the same order, try using the SequenceEqual method instead.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
-5

As an alternative, if you are not comfortable using LINQ you can use the System.Convert class...

byte[] a1;
byte[] a2;

if (System.Convert.ToBase64String(a1) == System.Convert.ToBase64String(a2)) {
    doSomething();
}
else {
    doSomethingElse();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kevin
  • 552
  • 2
  • 4
  • 6
    I would be "not confortable" converting two arrays to string and then iterating on the string again to make a comparison. I would prefer iterating just once using the LINQ method or making my own method. – Davi Fiamenghi Jul 24 '13 at 19:42
  • 1
    Terribly and needlessly inefficient. Like Davi Fiamenghi said, either use SequenceEqual or just do simple loop comparison. – chris Apr 10 '15 at 12:35
  • It would depend on the whether one side of the comparison is already in base64 though, in which case you may as well convert the other side. This scenario is reasonably common when you want to present human readable byte[] arrays. For example, when using hashes for document verification – Sam Shiles Feb 09 '17 at 09:59