Arrays are Structurally equatable in .NET 4.0


Arrays are Structurally equatable in .Net 4.0

In .NET 4.0, arrays can implement the IStructuralEquatable, which let's you equate two arrays based on their contents. This provide the support for comparison of objects for structural equality.

Example for standard arrays:-

int[] arr1 = new int[]

{

 1,2,3

};

int[] arr2 = new int[]

{

 1,2,3

};

IStructuralEquatable equate = arr1;

Console.WriteLine(equate.Equals(arr2, EqualityComparer<int>.Default));


The output will return true since both arrays are equal.

For Object arrays

public class Customer:IEquatable<Customer>

{

    public int CustomerId;

    public int CustomerName;

    public bool Equals(Customer other)

    {

        return this.CustomerId == other.CustomerId &&

        this.CustomerName == other.CustomerName;

    }

}

 

var customer = new []

{

    new Customer()

    {

        CustomerId=1,CustomerName=2

    },

    new Customer()

    {

        CustomerId=2,CustomerName=1

    }

};

 

var customer2 = new []

{

    new Customer()

    {

        CustomerId=1,CustomerName=2

    },

    new Customer()

    {

        CustomerId=2,CustomerName=1

    }

};

IStructuralEquatable equate1 = customer;

Console.WriteLine(equate1.Equals(customer2, EqualityComparer<Customer>.Default));



This will return true since both custom arrays are equal.

Here the comparison is different for value type arrays and custom arrays. In .Net 4.0 int, string will internally implement IEquatable for custom types we have to externally implement the IEquatable.

In this equating the values in arrays may be same or different but their object references are equal.

Similarly we can use IStructuralComaparable for comparison of one object with another.


Similar Articles