Have I just forgotten the obvious, or is the "manual" comparer the best way to go?
Basically, I just want to compare the contents of type (small) byte-arrays. If all bytes match, the result should be true, otherwise false.
I was expecting to find that Array.Equals
or Buffer.Equals
would help.
Demonstration Code:
var a = new byte[]{1, 2, 3, 4, 5};
var b = new byte[]{1, 2, 3, 4, 5};
Console.WriteLine(string.Format("== : {0}", (a == b)));
Console.WriteLine(string.Format("Equals : {0}", a.Equals(b)));
Console.WriteLine(string.Format("Buffer.Equals : {0}", Buffer.Equals(a, b)));
Console.WriteLine(string.Format("Array.Equals = {0}", Array.Equals(a, b)));
Console.WriteLine(string.Format("Manual_ArrayComparer = {0}", ArrayContentsEquals(a, b)));
Manual function:
/// <summary>Returns true if all elements of both byte-arrays are identical</summary>
public static bool ArrayContentsEquals(byte[] a, byte[] b, int length_to_compare = int.MaxValue)
{
if (a == null || b == null) return false;
if (Math.Min(a.Length, length_to_compare) != Math.Min(b.Length, length_to_compare)) return false;
length_to_compare = Math.Min(a.Length, length_to_compare);
for (int i = 0; i < length_to_compare; i++) if (a[i] != b[i]) return false;
return true;
}