What is operator?
Operators are the symbols, which are used to perform an operation between the operands. As,
a + b
Operands : a and b
Operator : +
Type of operators:
Operators are of two types, which are:
Unary Operators : ++, --, -
Binary Operators : +, -, *, /, >, <, =, == etc.
Why operator overloading is required?
Usually, the operators work with the pre-defind type like int, float, string etc. If you want to perform an operation on the user defined type (object), it is required to re-define the operators (overload) to perform the operation.
- Number n1=new Number(10,20);
- Number n2=new Number(5,10);
- Number n3=n1+n2;
n1 and n2 are two user defined types (object) and + operator is required to perform an addition between the two objects. This is only possible with the operator overloading.
Example:
Create a class to define a user defined type (object).
- class Numbers
- {
- public int num1, num2;
- public Numbers()
- {
- num1 = 0;
- num2 = 0;
- }
- public Numbers(int a,int b)
- {
- num1 = a;
- num2 = b;
- }
- public void PrintNumbers()
- {
- Console.WriteLine("Num1 :"+num1);
- Console.WriteLine("Num2 :" + num2);
- }
- }
Write the code to redefine the operators (overload) to perform a user defined operation.
Operator overloading : +
- public static Numbers operator +(Numbers ob1, Numbers ob2)
- {
- Numbers ob3 = new Numbers();
- ob3.num1 = ob1.num1 + ob2.num1;
- ob3.num2 = ob1.num2 + ob2.num2;
- return ob3;
- }
Operator overloading : ++
- public static Numbers operator ++(Numbers ob1)
- {
- Numbers ob2 = new Numbers ();
- ob2.num1 = ob1.num1 + 1;
- ob2.num2 = ob1.num2 + 1;
- return ob2;
- }
Operator overloading : >

Bhuvan PandeyPosted Sep 14, 2016, 1:35 AM
Thanks Subash.
SubashPosted Sep 14, 2016, 12:26 AM
Nice one
Bhuvan PandeyPosted Aug 8, 2016, 7:47 AM
Thanks.
Nikhil SanganiPosted Aug 8, 2016, 7:44 AM
Nice.