Operator Overloading
Operator overloading allows for the specification of user-defined implementations of operators in operations involving one or two operands of a user-defined class or struct type.
Operator overloading delivers more capabilities when applied to user-defined data types. Only unary, binary, and comparison operators can be overloaded; however, comparison operators have a restriction. Comparison operators must be overloaded in pairs, e.g., overload both the < and > operators.
The conditional logical, indexing, cast, assignment, and those that follow cannot be overloaded:
= | checked |
. | unchecked |
?: | default |
?: | default |
?? | delegate |
-> | is |
=> | new |
f(x) | sizeof |
as | typeof |
Note that despite any restrictions new conversion operators can be defined, and indexers can be defined.
OVERLOADING
Create a method in a custom class with the right signature for overloading. Use the keyword operator followed by the operator or operator name to name the method. Follow the name with a single parameter for unary operators and two parameters for binary operators. One parameter must be of a type identical to the class or struct in which its declaration appears. Review an example of an operator overload below:
public static Cube operator+ (Cube x, Cube y) { Cube cube = new Cube(); cube.length = x.length + y.length; cube.breadth = x.breadth + y.breadth; cube.height = x.height + y.height; return cube; }
The previous method employs the + operator in a user-defined class named “Cube.” After adding the attributes of 2 Cube objects, it returns the resulting Cube object.
The shortcut tool (=>) can be applied to the method. Consider this example:
public static Complex operator +(Complex cx, Complex cy) => new Complex(cx.real + cy.real, cx.imaginary + cy.imaginary);