What is operator overloading in c#?

Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type. Overloaded operators are functions with special names the keyword "operator" followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list. This feature is not present in C#’s competitor language Java, which makes C# appealing to the many programmers who are building large libraries/frameworks.

You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Suppose that simply with "+" operator you eligible to add numeric parameters. But Suppose that you have a box class. Which has two property Height and Width. You create three instance of the class box_1, box_2, sizeOfBoxes.

Guess you want to add the size of two boxes and assign it to third one. Now if you simply add the two boxes and assign it to the third one obviously that will make error.

Because you can not add two object with plus operator. You have to overload the operator to define the task of "+" operator within the class when two operand is instance of rectangle class.


The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object. Now you can make a call to overloaded operator method from where it is accessible. Not all operators can be overloaded, however, and others have restrictions, as listed in this table:

Overloadable Operators in C#

A simple way to make your code less ambiguous is to provide the equivalent methods for overloaded-operators. So, for instance, if a user of your library can't understand operators that you have overloaded , then he/she can anyway use methods for achieving the same results.
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About