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 
        }
    }
}

9 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
  4. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. Python Training in Chennai

    ReplyDelete
  5. Interesting blog post. This blog shows that you have a great future as a content writer. Java Training in Chennai | RPA Training in Chennai

    ReplyDelete
  6. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.Trending Software Technologies in 2018 | Hadoop Training in Chennai | big data Hadoop training and certification in Chennai

    ReplyDelete