Operator Overloading in C# Definition with example

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.
$ads={2}
operator overloading in c#



Definition of Operator overloading in c#

The class allows creating a user to define the type of 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 supports few operators. and (Assignment operator), by using operator overloading in c# we can enhance the capabilities of an object to support the operator.

$ads={1}

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();

    }
}




READ MORE-KNOW MORE








Post a Comment

Post a Comment (0)

Previous Post Next Post