List of Overloadable Operators in C# (C Sharp)
overloading is an interesting feature of Object Oriented Programming.
Operator overloading is an example of polymorphism. In general, each operator
has a definite meaning.
Click Here To Try It FREE for 7 days
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:
Operators: +, -, ++, --, ~, !, true, false
While overloading comparison operators, ensure the following:
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:
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.
to our mailing list and receive new articles Note
: We never rent, trade, or sell my email lists to Visit
.NET Programming Tutorial Homepage ______________________________________________________
to our mailing list and receive new articles
: We never rent, trade, or sell my email lists to
Visit .NET Programming Tutorial Homepage
| Design Guideline for C# Structs (C Sharp) | Design Patterns Its Importance and Types | How to Implement Proxy Pattern Using C# (C Sharp)? | How to Implement Singleton Pattern Using C# (C Sharp)? | Illustration of Abstract Classes of C# (C Sharp) with Examples | Illustration of Sealed Classes of C# (C Sharp) with Examples | List of Overloadable Operators in C# (C Sharp) | Usage of [ ] and () Operators in C# (C Sharp) | What is C# (C Sharp) Nested Type? |