How to implement the - (minus) operator overloading in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    public class Complex
    {
        public int x;
        public int y;

        public Complex(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        // operator overload (-)
        public static Complex operator -(Complex com1, Complex com2)
        {
            return new Complex(com1.x - com2.x, com1.y - com2.y);
        }

        public override string ToString()
        {
            return (String.Format("{0} - {1}", x, y));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Complex complex1 = new Complex(11, 15);
            Complex complex2 = new Complex(3, 4);

            Complex sum_complex = complex1 - complex2;

            Console.WriteLine("complex1 = {0}", complex1);
            Console.WriteLine("complex2 = {0}", complex2);

            Console.WriteLine("sum_complex = {0}", sum_complex);
        }
    }
}



/*
run:

complex1 = 11 - 15
complex2 = 3 - 4
sum_complex = 8 - 11

*/

 



answered Apr 27, 2017 by avibootz

Related questions

2 answers 246 views
1 answer 200 views
1 answer 193 views
193 views asked Mar 16, 2017 by avibootz
1 answer 216 views
2 answers 272 views
1 answer 250 views
250 views asked Sep 6, 2015 by avibootz
1 answer 144 views
144 views asked Dec 2, 2022 by avibootz
...