C# Program to Overload Binary minus Operator ‘-‘

You are currently viewing C# Program to Overload Binary minus Operator ‘-‘

C# program to overload binary minus 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 : 30
Value : 20
Value : 10

Ranjith Kumar

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

Leave a Reply