Search code examples
c#comparisonbinaryarraysequality

I want to have an Extension method "Equals" between 2 byte arrays


I am doing some byte[] comparisons.

I tried == but this is just like the base Equals, which:

byte[] a = {1,2,3};
byte[] b = {1,2,3};
bool equals = a == b; //false
equals = a.Equals(b); //false

I tried to add an extension method, but since the overloaded base class' Equals takes the same arguments, it goes to the base method rather to the extension, is there anyway I can use an Equals extension (wthout changing it's name...) or (even better) use == operator?

Here is what I actually have to Compare:

public static bool ContentEquals(this byte[] array, byte[] bytes)
{
    if (array == null || bytes == null) throw new ArgumentNullException();
    if( array.Length != bytes.Length) return false;
    for (int i = 0; i < array.Length; i++)
        if (array[i] != bytes[i]) return false;

    return true;
}

Solution

  • using System.Linq;
    
    byte[] a = {1,2,3}; 
    byte[] b = {1,2,3}; 
    bool same = a.SequenceEqual(b);