FREE BOOK

Chapter 2: Creating Versatile Types

Posted by SAMS Publishing Free Book | C# Language March 24, 2010
Tags: C#
This chapter is all about making your own objects as useful and versatile as possible. In many cases, this means implementing the standard interfaces that .NET provides or simply overriding base class methods.

Make Types Equatable

Scenario/Problem: You need to determine if two objects are equal.

Solution: 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().

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;
    }
}

NOTE: 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.

Total Pages : 12 34567

comments