Operator Overloading
Learn to overload operators.
We'll cover the following...
C# provides various operators for performing arithmetics and comparison. Some examples are +
, -
, >
, and <
.
It’s intuitive to use such operators with numeric types:
int sum = 4 + 7; // 11
int difference = 18 - 2; // 16
bool areEqual = sum == difference; // false
To use these operators with user-defined types, we can overload needed operators.
Overloading arithmetic operators
In C#, we can overload arithmetic operators ( +
, -
, /
, *
, %
).
Let’s first define ...