Friday, December 24, 2010

C# Tutorial: Operator Overloading [Add 2 Complex Numbers]

Here is the code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Complex
    {
        int real, imaginary;

        Complex(int real, int imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }

        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);   
        }

        public override string ToString()
        {
            return string.Format("{0} + {1}i", real, imaginary);   
        }

        static void Main(string[] args)
        {
            Complex c1 = new Complex(4, 3);
            Complex c2 = new Complex(7, 9);
            Complex sum = c1 + c2;
            Console.WriteLine("The sum of the two complex numbers is: {0}", sum);
            Console.ReadKey(); // Pause 
        }
    }
}

3 comments:

  1. Thanks for sharing your thoughts. I truly appreciate your efforts and I am waiting for your next write ups thanks once again.

    Rica
    www.imarksweb.org

    ReplyDelete
  2. Thanks for sharing your thoughts. I truly appreciate your efforts and I am waiting for your next write ups thanks once again.

    Rica
    www.imarksweb.org

    ReplyDelete
  3. Thanks but i have a question, how could i do with minus ? Is it the same only where is plus put I minus?

    ReplyDelete