C# Operator Overloading
Here is the C# Operator Overloading Defination and Example.
Operator Overloading Details
In an object oriented programming language like C#, operator overloading provides a much more natural way of implementing the operations on custom types. Suppose that we have a class created for Complex number and we want to perform all the arithmetic operations on this type. One way to do this is by having functions like Add, Subtract inside the class and have the functionality. Another way is to actually have the overloaded version of operators to act on this type.
Operator overloading provides a much natural abstraction for the types. When we think about possible operation on some data type we can think of binary operators, unary operators, relational operators and perhaps some conversion operations to and from the basic types. In C# achieving all this is possible using operator overloading.
Using the code
Before looking at the implementation details, lets see what are the conventions that need to be followed if we want to overload an operator.
- The operator function should be a member function of the containing type.
- The operator function must be
static
.
- The operator function must have the keyword operator followed by the operator to be overridden.
- The arguments of the function are the operands.
- The return value of the function is the result of the operation.