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

1

4 Answers 4

74

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

-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();
}

3 Comments

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.
Terribly and needlessly inefficient. Like Davi Fiamenghi said, either use SequenceEqual or just do simple loop comparison.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.