Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   Overload Appropriate Operators (http://www.go4expert.com/forums/overload-appropriate-operators-t21341/)

arunlalds 13Mar2010 15:14

Overload Appropriate Operators
 
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.
Code:

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

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:
Code:

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



All times are GMT +5.5. The time now is 05:59.