Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Implement the IEquatable<T> Interface

I have been reading articles and understand interfaces to an extent however, if i wanted to right my own custom Equals method, it seems I can do this without implementing the IEquatable Interface. An example.

using System;
using System.Collections;
using System.ComponentModel;

namespace ProviderJSONConverter.Data.Components
{
    public class Address : IEquatable<Address>
    {
        public string address { get; set; }

        [DefaultValue("")]
        public string address_2 { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string zip { get; set; }

        public bool Equals(Address other)
        {
            if (Object.ReferenceEquals(other, null)) return false;
            if (Object.ReferenceEquals(this, other)) return true;
            return (this.address.Equals(other.address)
                && this.address_2.Equals(other.address_2)
                && this.city.Equals(other.city)
                && this.state.Equals(other.state)
                && this.zip.Equals(other.zip));
        }
    }
 }

Now if i dont implement the interface and leave : IEquatable<Address> out of the code, it seems the application operates exactly the same. Therefore, I am unclear as to why implement the interface? I can write my own custom Equals method without it and the breakpoint will hit the method still and give back the same results. Can anyone help explain this to me more? I am hung up on why include "IEquatable<Address>" before calling the Equals method.

like image 301
devzim Avatar asked Nov 29 '22 01:11

devzim


1 Answers

Now if i dont implement the interface and leave : IEquatable out of the code, it seems the application operates exactly the same.

Well, that depends on what "the application" does. For example:

List<Address> addresses = new List<Address>
{
    new Address { ... }
};
int index = addresses.IndexOf(new Address { ... });

... that won't work (i.e. index will be -1) if you have neither overridden Equals(object) nor implemented IEquatable<T>. List<T>.IndexOf won't call your Equals overload.

Code that knows about your specific class will pick up the Equals overload - but any code (e.g. generic collections, all of LINQ to Objects etc) which just works with arbitrary objects won't pick it up.

like image 100
Jon Skeet Avatar answered Dec 10 '22 12:12

Jon Skeet