Make Types Equatable

Discussion in 'C#' started by arunlalds, Mar 13, 2010.

  1. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    You should override Object.Equals() and also implement the
    IEquatable<T> interface.
    By default, Equals() on a reference type checks to see if the objects refer to the same
    location in memory. This may be acceptable in some circumstances, but often, you’ll
    want to provide your own behavior. With value types, the default behavior is to reflect
    over each field and do a bit-by-bit comparison. This can have a very negative impact
    on performance, and in nearly every case you should provide your own implementation
    of Equals().
    Code:
    struct Vertex3d : IFormattable, IEquatable<Vertex3d>
    {
    ...
    public override bool Equals(object obj)
    {
    if (obj == null)
    return false;
    if (obj.GetType() != this.GetType())
    return false;
    return Equals((Vertex3d)obj);
    }
    public bool Equals(Vertex3d other)
    {
    /* If Vertex3d were a reference type you would also need:
    * if ((object)other == null)
    * return false;
    *
    * if (!base.Equals(other))
    * return false;
    */
    return this._x == other._x
    && this._y == other._y
    && this._z == other._z;
    }
    }
    
    Pay special attention to the note in Equals(Vertex3d other). If Vertex3d
    was a reference type and other was null, the type-safe version of the function would
    be called, not the Object version. You also need to call all the base classes in the
    hierarchy so they have an opportunity to check their own fields.
    There’s nothing stopping you from also implementing IEquatable<string> (or any
    other type) on your type—you can define it however you want. Use with caution,
    however, because this may confuse people who have to use your code.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice