/* The overloading method must be defined within the same class whose * objects are going to be used with the operator; else, compiler will complain: * One of the parameters of a binary operator must be the containing type. */ /* It is possible to use any kind of operators inside an overloaded operator * besides itself to perform manipulations on variables. */ /* Overloading + implicitly overloads += also. */ // Overloading the + operator public static Employee operator +(Employee emp_1, Employee emp_2) { Employee emp = new Employee(); emp.name = emp_1.name + " " + emp_2.name; emp.salary = emp_1.salary + emp_2.salary; return emp; }
static void Main(string[] args) { Employee emp_1 = new Employee(); Employee emp_2 = new Employee(); Employee emp_3 = new Employee(); System.Console.Write("Enter name of employee 1: "); emp_1.name = System.Console.ReadLine(); System.Console.Write("Enter salary of employee 1: "); emp_1.salary = Convert.ToInt32(System.Console.ReadLine()); System.Console.Write("\nEnter name of employee 2: "); emp_2.name = System.Console.ReadLine(); System.Console.Write("Enter salary of employee 2: "); emp_2.salary = Convert.ToInt32(System.Console.ReadLine()); emp_3 = emp_1 + emp_2; System.Console.WriteLine("\n\nWhen we apply + on the two objects of Employee class, result is -\n"); System.Console.WriteLine("Name: {0}", emp_3.name); System.Console.WriteLine("Salary: {0}", emp_3.salary); System.Console.ReadLine(); }