Operator overloading allows operators to be
redefined and used where one or both of the operands are of a user-defined class. When
done correctly, this can simplify the code and make user-defined types as easy to use
as the fundamental types. In this example we have a class called MyNum with an integer
field called val and a constructor for setting that field. We also have a static add method
that adds two MyNum objects together and returns the result as new object. If we create two
instances of MyNum we can use this method to add them together. What operator overloading does is allow us
to simplify this syntax and thereby provide a more intuitive interface for our class.
To convert the add method to an overload method for the addition sign we replace the name
of the method with the operator keyword followed by the operator that we want to overload.
The whitespace between the keyword and the operator can optionally be left out. Note
that for an operator overloading method to work it must be defined as both public and
static. Since the class now overloads the addition sign we can use this operator to
perform the needed calculation. Addition is a binary operator. That is, it
takes two operands. To overload a unary operator, such as the increment operator, we would instead
use a single method parameter. Note that this will overload both the postfix and prefix
versions of this operator. When overloading a unary operator the return
type and parameter type must be of the containing type. On the other hand when overloading most
binary operators the return type can be anything except for void and only one of the parameters
must be of the containing type. This means that it’s possible to further overload a binary
operator with other method parameters, for example to allow a MyNum and an integer to
be added together. C# allows overloading of almost all operators.
The combined assignment operators cannot be explicitly overloaded. Instead, they are implicitly
overloaded when their corresponding arithmetic or bitwise operators are overloaded. Another
things to keep in mind is that the comparison operators as well as true and false must be
overloaded in pairs. For example, overloading the equal operator means we also have to overload
the not equal operator. Notice here that true and false are considered
operators. By overloading them we can use objects of the class in conditional statements
where the object needs to be evaluated as a boolean type. Keep in mind that when overloading
true and false the return types must be boolean.