You certainly can't do operator overloading with extension methods. The reason it doesn't work for the Equals
method is that if any method is applicable without using extension methods, that method will be chosen before extension methods are even examined.
Even though your Equals
method is "better" in terms of converting the argument types to the formal parameter types, the compiler always prefers "normal" methods. You'll have to give your method a different name.
However, you can always use the Enumerable.SequenceEquals
method. I don't believe that short-circuits the length check though (even though it could, for ICollection<T>
implementations). You could always implement a more efficient version yourself though. Indeed, if you just change your existing array implementation to be called SequenceEquals
or even ArrayEquals
, that would be fine:
public static bool ArrayEquals(this byte[] array, byte[] bytes)
{
// I'd personally use braces in all of this, but it's your call
if (array.Length != bytes.Length) return false;
for (int i = 0; i < array.Length; i++)
if (array[i] != bytes[i]) return false;
return true;
}
Note that it would be quite nice to make it generic, but that would certainly cost a bit of performance as the comparison couldn't be inlined:
public static bool ArrayEquals<T>(this T[] first, T[] second)
{
// Reference equality and nullity checks for safety and efficiency
if (first == second)
{
return true;
}
if (first == null || second == null)
{
return false;
}
if (first.Length != second.Length)
{
return false;
}
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < first.Length; i++)
{
if (!comparer.Equals(first[i], second[i]))
{
return false;
}
}
return true;
}