Defining Operator Pairs


Defining Operator Pairs

Some operators naturally come in pairs. For example, if you can compare two Hour values by using the != operator, you would expect to be able to also compare two Hour values by using the == operator. The C# compiler enforces this very reasonable expectation by insisting that if you define either operator== or operator!=, you must define them both. This neither-or-both rule also applies to the < and > operators and the <= and >= operators. The C# compiler does not write any of these operator partners for you. You must write them all explicitly yourself, regardless of how obvious they might seem. Here are the == and != operators for the Hour struct:

struct Hour {     public Hour(int initialValue)     {         this.value = initialValue;     }     ...     public static bool operator==(Hour lhs, Hour rhs)     {         return lhs.value == rhs.value;     }     public static bool operator!=(Hour lhs, Hour rhs)     {         return lhs.value != rhs.value;     }     ...     private int value; }

The return type from these operators does not actually have to be Boolean. However, you would have to have a very good reason for using some other type or these operators could become very confusing!

NOTE
If you define operator== and operator!=, you should also override the Equals and GetHashCode methods inherited from System.Object. The Equals method should exhibit exactly the same behavior as operator== (define one in terms of the other). The GetHashCode method is used by other classes in the .NET Framework. (When you use an object as a key in a hash table for example, the GetHashCode method is called on the object to help calculate a hash value. For more information, see the .NET Framework Reference documentation supplied with Visual Studio 2005). All this method needs to do is return a distinguishing integer value (don't return the same integer from the GetHashCode method of all your objects though as this will reduce the effectiveness of the hashing algorithms).




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net