C# program to overload binary plus operator ‘+’

Everybody is exchanging information every day. That’s how we are going to exchange information about C# program to overload binary plus operator ‘+’ today.

C# program to overload binary plus operator '+'

C# program to overload binary plus operator ‘+’

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Sample
    {
        private int X;
        
        public Sample()
        {
            X = 0;
        }

        public void Set(int v)
        {
            X = v;
        }
        public static Sample operator +(Sample S1, Sample S2)
        {
            Sample temp = new Sample();

            temp.X = S1.X + S2.X;
           
            return temp;
        }

        public void printValue()
        {
            Console.WriteLine("Value : {0}", X);
        }
    }

    class Program
    {
        static void Main()
        {
            Sample S1 = new Sample();            
            Sample S2 = new Sample();
            Sample S3 = new Sample();

            S1.Set(10);
            S2.Set(20);

            S3 = S1 + S2;

            S1.printValue();
            S2.printValue();
            S3.printValue();
        }
    }
}
Value : 10
Value : 20
Value : 30

Final Words

We firmly believe that C# program to overload binary plus operator ‘+’ article will be very useful information for you. See you in the next article.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment