You are on page 1of 1

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 overloa ding 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 Declarat ion 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 even t 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.

You might also like