"I wish .NET can compare contents of an Array." - Annoymous Array Comparer
Currently, when you compare two arrays with the = operator, we are really using the System.Object's = operator, which only compares the instances. (i.e. this uses reference equality, so it will only be true if both arrays points to the exact same instance)
Well until we add this feature request in the framework itself, I've provided a temporary solution for you:
public static bool ArrayEquals<T>(T a, T b)
if (a.Length != b.Length)
for (int i = 0; i < a.Length; i++)
IL_0026: box !!TIL_002b: constrained. !!TIL_0031: callvirt instance bool [mscorlib]System.Object::Equals(object)
My office neighbour Brian Grunkemeyer have the following perf suggestions:
1) Add a generic constraint to this method
public static bool ArrayEquals<T>(T a, T b) where T: IEquatable<T>
This will help our performance, but limits the method to only take types that implement IEquatable<T>. This may be too restrictive for some though.
2) Use EqualityComparer<T>.Default's Equal method instead of calling Equals on the types themselves.
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
if (!comparer.Equals(a[i], b[i]))
Without measuring the perf of these on long arrays, my guess is that for value types #1 has the best perf, followed by #2 and then the original implementation.
What do you think?