2. Operator Overloading
Each C# operator has a predefined meaning. Most of them are given
additional meaning through the concept called operator overloading.
Main idea behind operator overloading is to use C# operators with the
class objects.
E.g.
‘+’ can be used to add 2 ints, floats and doubles, the same ‘+’ can be
used to add 2 class objects, thereby ‘+’ gets overloaded.
When an operator is overloaded, its original meaning is not lost.
3. Operator Overloading
Operator overloading can overload operators to work with class and
struct types.
Use keyword operator.
Follow with symbol
overload+
struct Point
{
int x;
int y;
public static Point operator+(Point p, Point q)
{
return new Point(p.x + q.x, p.y + q.y);
}
...
}
4. Using Overloaded Operator
Overloaded operator used like operators for other types.
Compiler translates into method call
use operator+
Point a = new Point(1, 2);
Point b = new Point(3, 4);
Point c = a + b;
5. Types of Operator Overloading
Binary Operators:
Binary operator works with two
parameters.
binary +
binary -
struct Point
{
int x;
int y;
public static Point operator+(Point p, Point q)
{
return new Point(p.x + q.x, p.y + q.y);
}
public static Point operator-(Point p, Point q)
{
return new Point(p.x - q.x, p.y - q.y);
}
...
}
6. Types of Operator Overloading
Unary Operators:
Unary operator works with single
parameter.
unary +
unary -
struct Point
{
int x;
int y;
public static Point operator+(Point p)
{
return new Point(p.x, p.y);
}
public static Point operator-(Point p)
{
return new Point(-p.x, -p.y);
}
...
}
7. Advantages of Operator Overloading
With operator overloading readability of the code improves.
With operator overloading the code becomes explicit in nature,
looking at the code, fellow developers can easily guess what is
going on.
With operator overloading the code looks more conventional and
becomes easy to follow.
The method defining operator overloading, should always be
static and public. Otherwise compiler error out with message
"User defined operator must always be static and public".
8. Limitations
Only some operators can be overloaded
Unary:
+ -! ~ ++ --true false
Binary:
+ -* / % & | ^ << >> == != > < >= <=
Cannot
o Create new operators.
o Change precedence.
o Change associativity.
o Change number of arguments.
o Overload prefix/postfix versions separately.
9. Summary
There are different ways in which operators may be overloaded
within C#. There are numerous ways that overloading can be used
to your advantage in custom classes and structs. It is now up to you
to decide how to best put it to use in your applications, and
important to remember that not all languages support operator
overloading.