Operator overloading in c# definition with example

Operator overloading in c# | Example 

In this article , I am going to discuss about operator overloading and it's example, Sometimes developers confused about it and they think operator overloading and function overloading is same but both are very different.

Definition of Operator overloading

Class allow to create user define type or extract datatype.If we create a variable of that type is set to be an object but that object doesn't support all the operators it support few operator like . and (Assignment operator) ,by using operator loading we can enhance the capabilities of an object to support the operator.


Point: 
1.Operator overloading works on early binding approach.
2.We can't operator overload at that function which approach decide at run-time.

Why we use operator overloading in c#
Used for to achieve object addition.

Steps for implementing operator overloading in c#
Here are some step that you need to follow while you are implementing operator overloading in c#.

1.Operator is a function is to be applied to support in built operator to given an object
2.Opeartor function should be static(See Example).
3.This function always takes two parameter ,can't have three parameter and must be public.
4.Note:We can't overload AND,OR,NOT like logical operator.
5.Operator function return the  object of 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();

    }
}




READ MORE-KNOW MORE







Previous
Next Post »