List of Overloadable Operators in C# (C Sharp)Operator
overloading is an interesting feature of Object Oriented Programming.
Operator overloading is an example of polymorphism. In general, each operator
has a definite meaning.
For example, + operator is used to add two numbers or concatenate two strings by taking two numbers or two strings as arguments correspondingly. Can this operator (+) be used with two class instances as parameters? No. This will end up in error. However you can make it possible by overloading + operator and defining a different meaning for it. This is demonstrated with relevant code in the later part of this article. Can you overload any operator of your choice? No. You cannot overload all the operators of C#. Only limited set of operators are eligible for overloading. They are listed below: Unary
Operators: +, -, ++, --, ~, !, true, false While overloading comparison operators, ensure the following: You
should overload != operator if you overload == operator and vice versa How can an operator be overloaded? To understand that, consider the + operator discussed in the beginning of this article. You are now going to overload this operator to operate on two class instances as shown below: class sampleClass
{ Output of this code will be: Instance3 member value is: 300 You achieved operator overloading by defining a static method using the keyword operator along with the operator + that has to be overloaded. Similarly, you can overload all other overloadable operators listed in this article.
|