C# Operator overloading | compile time polymorphism

Program

using System;

namespace Polymorphism
{
    class OperatorOverloading
    {
        class Product
        {
            string _ProductName;
            int _Price;
            int _Qty;

            public Product(string pname, int price, int qty)
            {
                _ProductName = pname;
                _Price = price;
                _Qty = qty;
            }

            public void displayProductDetails()
            {
                Console.WriteLine("Product Name : {0}", _ProductName);
                Console.WriteLine("Product Price : {0}", _Price);
                Console.WriteLine("Product Qty  : {0}", _Qty);
            }

            public static Product operator +(Product Pa, Product Pb)
            {
                Product Px = new Product("", 0, 0);
                Px._ProductName = Pa._ProductName + "," + Pb._ProductName;
                Px._Qty = Pa._Qty + Pb._Qty;
                Px._Price = Pa._Price + Pb._Price;
                return Px;
            }
        }
        static void Main(string[] args)
        {
            Product p1 = new Product("Keyboard", 450, 3);
            Product p2 = new Product("Mouse", 300, 5);
            Product p3;   
            p3 = p1 + p2;
            //Now p3 receives the address from px, so object referred
            //by px in operator+() method will also be referred by p3
            //because p3 didn't refer any object previously
            p1.displayProductDetails();
            p2.displayProductDetails();
            p3.displayProductDetails();
            Console.ReadKey();
        }

    }
}


Output

Product Name    : Keyboard
Product Price   : 450
Product Qty     : 3

Product Name    : Mouse
Product Price   : 300
Product Qty     : 5

Product Name    : Keyboard,Mouse
Product Price   : 750

Product Qty     : 8

No comments:

Post a Comment