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 1-3 lists the available overloadable operators.

Table 1-3. 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 to which the references point.

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.

Note

A good guideline for knowing whether to implement the == and != operators is ...

Get C# Language Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.