Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the reason why IEquatable<T> was introduced?

Tags:

c#

Is main reason why IEquatable<T> interface was introduced because it allows you to do the same as the System.Object.Equals method but without having to perform casts?

thank you

like image 923
flockofcode Avatar asked Apr 19 '11 20:04

flockofcode


3 Answers

To make it type safe, I would think. Equals() takes an object as parameter and hence you will not see an error if you pass in an object of wrong type until you run it.

like image 68
Bala R Avatar answered Sep 23 '22 23:09

Bala R


One reason is so that you can require a class be equatable with a desired type, without necessarily being that type. E.g.

public void MyClass<T> where T : IEquatable<Foo>
{
    private static readonly Foo SpecialFoo = Foo.SpecialFoo;

    public void MyMethodThatProcessesTs(T theT)
    {
        if (theT.Equals(SpecialFoo))
        {
            // process theT.
        }
    }
}
like image 22
Domenic Avatar answered Sep 22 '22 23:09

Domenic


In addition to what @Bala R says, it also avoids boxing when doing custom equality checking between structs.

like image 39
Jeffrey L Whitledge Avatar answered Sep 25 '22 23:09

Jeffrey L Whitledge