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 preceding the operator to overload
(instead of a method name), parameters representing the operands, and return
types representing the result of an expression. Table 4-1 lists the available
overloadable operators.
Table 4-1. Overloadable operators
+
|
-
|
!
|
~
|
++
|
--
|
+
|
-
|
* (binary only)
|
/
|
%
|
& (binary only)
|
|
|
^
|
<<
|
>>
|
==
|
!=
|
>
|
<
|
>=
|
<=
|
Literals that also act as overloadable operators are true and false.
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 variables by reference. However, it is occasionally
more natural for the == and !=
operators to exhibit value equality, whereby the comparison is based
on the value of the objects that the references point to.
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.
Tip
A good guideline for knowing whether to implement the
== and != operators is if it is natural for the class to overload ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access