Home »
C# programming
What is Operator Overloading in C#?
In this article, we are going to learn about operator overloading in C#, here, we will also learn - which operators can be overloaded and which cannot be overloaded?
Submitted by IncludeHelp, on February 18, 2018
C# - Operator Overloading
It is a type of polymorphism. As we know that every operator has a pre-defined implementation. But using operator overloading we can assign some special task to c# operators with respect to user defined data-type like classes and structures.
We can overload some C# operators; all C# operators cannot be overloaded. We can overload following operators that are given below:
- Arithmetic operators (+ - * / %)
- Bitwise operators (& | << >>)
- Unary operators (+ - ! ~ ++ --)
- Relational operators (== != < > <= >=)
- Compound assignment (+= -= *= /= %=)
We cannot overload following operators are given below:
- Logical operators (&& ||)
- Conversion operator ( () )
- Assignment operator ( = )
- Dot or membership operator ( . )
- Conditional or ternary operator ( ?: )
- Referential operator ( -> )
- New operator ( new )
- Size of operator ( sizeof() )
In C#, to overload any allowed operator we need to use operator keyword. Here we create a method with given operator like + , - and operator keyword. This method must be public and static. This method can take only value arguments, here we cannot use ref or out parameters.
Syntax:
public static return_type operator op (Type t)
{
// Statements
}
Here, Type must be a class or strurct.