4.5 Operator Overloading
C# lets you overload operators to work with operands that are custom classes or structs using operators. An operator is a static method with the keyword
operator
Table 4-1. Overloadable operators
Literals that also act as overloadable operators are true and false . 4.5.1 Implementing Value Equality
A pair of references exhibit referential equality when both references point to the same object. By default, the
= =
and
!=
operators will compare two reference-type
Whenever overloading the = = and != operators, you should always override the virtual Equals method to route its functionality to the = = operator. This allows a class to be used polymorphically (which is essential if you want to take advantage of functionality such as the collection classes). It also provides compatibility with other .NET languages that don't overload operators.
class Note {
int value;
public Note(int semitonesFromA) {
value = semitonesFromA;
}
public static bool operator = =(Note x, Note y) {
return x.value = = y.value;
}
public static bool operator !=(Note x, Note y) {
return x.value != y.value;
}
public override bool Equals(object o) {
if(!(o is Note))
return false;
return this = =(Note)o;
}
}
Note a = new Note(4);
Note b = new Note(4);
Object c = a;
Object d = b;
// To compare a and b by reference
Console.WriteLine((object)a = =(object)b; // false
//To compare a and b by value:
Console.WriteLine(a = = b); // true
//To compare c and d by reference:
Console.WriteLine(c = = d); // false
//To compare c and d by value:
Console.WriteLine(c.Equals(d)); // true
4.5.2 Logically Paired OperatorsThe C# compiler enforces operators that are logical pairs to both be defined. These operators are = = != , < > , and <= >= . 4.5.3 Custom Implicit and Explicit Conversions
As explained in the discussion on types, the rationale behind implicit conversions is they are
...
// 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
4.5.4
|