C# Program to Overload a Unary minus Operator ‘-‘

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

C# program to overload a unary minus operator ‘-‘

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Sample
    {
        private int X;
        private int Y;

        public Sample()
        {
            X = 10;
            Y = 20;
        }

        public static Sample operator-(Sample S)
        {
            Sample temp = new Sample();

            temp.X = -S.X;
            temp.Y = -S.Y;

            return temp;
        }

        public void printValue()
        {
            Console.WriteLine("{0},{1}", X, Y);
        }
    }

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

            S1.printValue();

            Sample S2 = new Sample();
            S2.printValue();

            S2 = -S1;

            S2.printValue();

        }
    }
}
10,20
10,20
-10,-20

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