• Now Online : 37
  • admin@codemyne.net

Introduction

Operator is designed to use only with numbers and strings but not with objects. In case it is used with objects, then it need to be overloaded. Operator overloading is the concept of extending the functionality of an existing operator. All the operators are overloadable except those contains a dot.

That is following operators are not overloadable.

  • Member access operator (.)
  • Inheritance operator (:)
  • Property access operator (::)
  • Ternary operator (?)

While overloading relational operators, these must be overloaded in PAIR.

  • To overload > , < must be overloaded
  • To overload >= , <= must be overloaded
  • To overload != , == must be overloaded

Overloaded operator must be declared as static. Operator is a keyword.

Syntax to overload an operator.

public static returntype operator + (args)

Example: Overloading '+' operator to add the salaries of two employees (objects)

Create a new windows project in C#. Place the following code in General Declaration part.

class Emp
{
    private int sal;
    public Emp(int x)
    {
        sal = x;
    }
    public static int operator +(Emp a, Emp b)
    {
        int i = a.sal + b.sal;
        return i;
    }
}

Now place a button on the form and paste the following code in button click event

Emp e1 = new Emp(5000);
Emp e2 = new Emp(15000);
int total = e1 + e2;
MessageBox.Show(total.ToString());    

Click on the button to see the result. From this example two Emp objects can be added by using operator overloading.

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment

fringer 4/26/2012 (IST) / Reply

simple and crisp... thanks

fazal 7/26/2012 (IST) / Reply

very easy way to define ,Thanks.

siva 8/13/2012 (IST) / Reply

Its Very example for me. thanks

sagar 12/19/2012 (IST) / Reply

hi sir its very easy easy example for me. but could i know Why does C# require operator overloads to be static methods rather than member functions (like C++)?

ABC 2/8/2013 (IST) / Reply

very usefulllllll .thank uuuuuuu

Ratan Kumar 10/8/2013 (IST) / Reply

Very Simple way to define and easy to understand.... I found it one of the best article over internet.....

yuuuuuuuuuu 7/17/2015 (IST) / Reply

uuuuuuuuuuuuuuuuuuuuuuu