C# Code for Operator overloading

using System;

namespace PostSlush
{
    class Complex
    {
        double x;       //real part
        double y;       //imaginary part

        public void read()
        {
            Console.Write("\n Enter real part : ");
            x = double.Parse(Console.ReadLine());
            Console.Write("\n Enter imaginary part : ");
            y = double.Parse(Console.ReadLine());
        }
        public static Complex operator +(Complex c1, Complex c2)
        {
            Complex c = new Complex();
            c.x = c1.x + c2.x;
            c.y = c1.y + c2.y;
            return (c);
        }
        public static Complex operator -(Complex c1, Complex c2)
        {
            Complex c = new Complex();
            c.x = c1.x - c2.x;
            c.y = c1.y - c2.y;
            return (c);
        }
        public void Display()
        {
            Console.WriteLine("(" + x + ")" + " + i" + "(" + y + ")");
        }
    }
    class ComplexTest
    {
        public static void Main()
        {
            Complex a = new Complex();
            Console.WriteLine("\n a (Complex number1) : ");
            a.read();
            Complex b = new Complex();
            Console.WriteLine("\n\n b (Complex number2) : ");
            b.read();
            Complex c = a + b;
            Complex d = b - a;
            Console.Write("\n\n a = ");
            a.Display();
            Console.Write("\n\n b = ");
            b.Display();
            Console.Write("\n\n c = a + b : ");
            c.Display();
            Console.Write("\n\n d = b - a : ");
            d.Display();
            Console.ReadLine();
        }
    }

}
Previous Post Next Post