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