Determine if two arrays are structurally equal in C# .NET

Two arrays are said to be structurally equal if they contain the same elements in the same order. Whether or not two elements are the same depends on how you define equality for your custom types. Equality for primitive types, like integers, is more or less straightforward but you’ll need to declare in code what is meant by equality for reference types.

The non-generic IStructuralEquatable interface has an equals method that accepts an object to compare with and another object which implements the non-generic IEqualityComparer interface. This is an important distinction as implementing the generic IEqualityComparer interface won’t be enough for structural equality. We’ll need to derive from the EqualityComparer base class which implements both the generic and non-generic version of IEqualityComparer. If you try to run the below example with a generic IEqualityComparer of T instance then you’ll get a compiler error.

Note that structural equality is not available for all collection types. Currently only arrays and tuples support it, i.e. they can be cast to type IStructuralEquatable. However, as List objects can be easily converted into arrays that’s not really an obstacle.