Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two arrays of bytes [duplicate]

Tags:

arrays

c#

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!!!

like image 600
Michael Avatar asked Sep 11 '25 04:09

Michael


2 Answers

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
like image 188
Darin Dimitrov Avatar answered Sep 12 '25 18:09

Darin Dimitrov


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.

like image 33
SLaks Avatar answered Sep 12 '25 16:09

SLaks