Overloading Operators in C# - Overloading Equality and Comparison Operators
(Page 3 of 4 )
Equality and comparison operators are sometimes overridden when writing structs, and in rare cases when writing classes. Special rules and obligations come with overloading the equality and comparison operators, which we explain in Chapter 6. A summary of these rules is as follows:
Pairing
The C# compiler enforces operators that are logical pairs to both be defined. These operators are (==!=), (<>), and (<= >=).
Equalsand GetHashCode
In most cases, if you overload (==) and (!=), you need to override theEquals andGetHashCode methods defined onobjectin order to get meaningful behavior. The C# compiler will give a warning if you do not do this. (See the section “Equality comparison ” in Chapter 6 for more details.)
IComparableand IComparable<T>
If you overload (<>) and (<= >=), you should implementIComparableand IComparable<T>.
Custom Implicit and Explicit Conversions
Implicit and explicit conversions are overloadable operators. These conversions are typically overloaded to make converting between strongly related types (such as numeric types) concise and natural.
To convert between weakly related types, the following strategies are more suitable:
- Write a constructor that has a parameter of the type to convert from.
WriteToXXX andFromXXX methods to convert between types.
As explained in the discussion on types, the rationale behind implicit conversions is that they are guaranteed to succeed and do not lose information during the conversion. Conversely, an explicit conversion should be required either when runtime circumstances will determine whether the conversion will succeed or if information may be lost during the conversion.
In this example, we define conversions between our musicalNotetype and a double (which represents the frequency in hertz of that note):
...
// Convert to hertz
public static implicit operator double(Note x)
{
return 440 * Math.Pow (2,(double) x.value / 12 );
}
// Convert from hertz (only accurate to nearest semitone)
public static explicit operator Note(double x)
{
return new Note ((int) (0.5 + 12 * (Math.Log(x/440) / Math.Log(2)) ));
}
...
Note n =(Note)554.37; // explicit conversion
double x = n; // implicit conversion
Following our own guidelines, this example might be better implemented with aToFrequencymethod (and a staticFromFrequencymethod) instead of implicit and explicit operators.
Next: Overloading true and false >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|