Operator Overloading in c# Example
In this article, I am going to discuss operator overloading in c# and its example, Sometimes developers confused about it and think operator overloading and function overloading is the same but both are very different.
Definition of Operator overloading in c#
Point:
1. Operator overloading works on the early binding approach.
2. We can't operator overload at that function which approaches decide at run-time.
Why we use operator overloading in c#
Used to achieve object addition.
Steps for implementing operator overloading in c#
Here is some step that you need to follow while you are implementing operator overloading in c#.1. The operator is a function that is to be applied to support an inbuilt operator to given an object
2. The operator function should be static(See Example).
3. This function always takes two parameters, can't have three parameters and must be public.
4. Note: We can't overload AND, OR, NOT like a logical operator.
5. Operator function returns the object containing class.
Example of Operator overloading
using System;
class office
{
double salary;
public office()
{
salary = 0;
}
public office(double sal)
{
salary = sal;
}
public void Display()
{
Console.WriteLine(salary);
}
public static office operator +(office o,office ob) //it must be public static otherwise get compiler error
{
office obj = new office();
obj.salary = o.salary + ob.salary;
return obj;
}
static void Main()
{
office a = new office(1212);
office b = new office(7888);
office accuntant = new office();
accuntant = a + b;
accuntant.Display();
}
}
Post a Comment