Home » C# programs

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

In this article, we will learn how to overload a unary minus operator in C#? Here, we will create a sample class with two data member X and Y. assign value using default constructor.
Submitted by IncludeHelp, on February 22, 2018

Program to overload unary minus (-) operator in C#

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();

        }
    }
}

Output

10,20
10,20
-10,-20

In this program, we created two object of class sample S1 and S2. And print the values of both objects before and after operator overloading.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.