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.

Overload Appropriate Operators

Scenario/Problem: You want to define what the +, *, ==, and != operators do when called on your type.

Solution: Operator overloading is like sugar: a little is sweet, but a lot will make you sick. Ensure that you only use this technique for situations that make sense.

Implement operator +

Notice that the method is public static and takes both operators as arguments.

public static Vertex3d operator +(Vertex3d a, Vertex3d b)
{
   return new Vertex3d(a.X + b.X, a.Y + b.Y, a.Z + b.Z);

}

The same principal can be applied to the -, *, /, %, &, |, <<, >>, !, ~, ++, and -- operators as well.

Implement operator == and operator !=

These should always be implemented as a pair. Because we've already implemented a useful Equals() method, just call that instead.

public static bool operator ==(Vertex3d a, Vertex3d b)
{
    return a.Equals(b);
}

public
static bool operator !=(Vertex3d a, Vertex3d b)
{
    return !(a==b);

}

What if the type is a reference type? In this case, you have to handle null values for both a and b, as in this example:

public static bool operator ==(CatalogItem a, CatalogItem b)
{
    if ((object)a == null && (object)b == null)
        return true;
    if ((object)a == null || (object)b == null)
        return false;
    return a.Equals(b);
}

public
static bool operator !=(CatalogItem a, CatalogItem b)
{
    return !(a == b);

}

Total Pages : 12 89101112

comments