.NET 4.0 : Arrays are now structurally equatable

In .NET 4.0, arrays implement IStructuralEquatable which lets you equate two arrays based on their contents.

int[] array1 = new int[] { 3, 5, 9 };
int[] array2 = new int[] { 3, 5, 9 };

IStructuralEquatable equatableArray1 = array1;
Console.WriteLine(
    equatableArray1.Equals(
        array2, EqualityComparer<int>.Default));

The above code outputs True. You can use it with your custom types too :

class Person : IEquatable<Person>
{
    public string Name { get; set; }

    public int Age { get; set; }

    public bool Equals(Person other)
    {
        return this.Name == other.Name && this.Age == other.Age;
    }
}

var person1 = new[]
{
    new Person() { Name = "John", Age = 17 },
    new Person() { Name = "Alice", Age = 18 }
};

var person2 = new[] {
    new Person() { Name = "John", Age = 17 },
    new Person() { Name = "Alice", Age = 18 }
};

IStructuralEquatable equatablePersonArray1 = person1;
Console.WriteLine(
    equatablePersonArray1.Equals(
        person2, EqualityComparer<Person>.Default));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s