How to use operator overloading in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication1
{
    public struct o_overloading
    {
        public int x;
        public int y;

        public o_overloading(int nx, int ny)
        {
            x = nx;
            y = ny;
        }

        // Operator overload + 
        public static o_overloading operator +(o_overloading o1, o_overloading o2)
        {
            return new o_overloading(o1.x + o2.x, o1.y + o2.y);
        }

        // Override the ToString() method
        public override string ToString()
        {
            return (string.Format("{0} + {1}", x, y));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                o_overloading xy1 = new o_overloading(1, 6);
                o_overloading xy2 = new o_overloading(13, 9);

                // Add two objects with overloaded + operator:
                o_overloading sum = xy1 + xy2;

                // Print the numbers with the overloaded ToString() method
                Console.WriteLine("xy1:  {0}", xy1);
                Console.WriteLine("xy2: {0}", xy2);
                Console.WriteLine("xy1 + xy2: {0}", sum);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
     
xy1:  1 + 6
xy2: 13 + 9
xy1 + xy2: 14 + 15
   
*/

 



answered Sep 6, 2015 by avibootz
edited Mar 13, 2017 by avibootz

Related questions

1 answer 244 views
2 answers 248 views
1 answer 201 views
1 answer 144 views
144 views asked Dec 2, 2022 by avibootz
7 answers 410 views
410 views asked Mar 13, 2017 by avibootz
1 answer 226 views
1 answer 222 views
...