Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,859 questions

51,780 answers

573 users

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 210 views
2 answers 228 views
1 answer 190 views
1 answer 134 views
134 views asked Dec 2, 2022 by avibootz
7 answers 378 views
378 views asked Mar 13, 2017 by avibootz
1 answer 214 views
1 answer 209 views
...