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

Problem statement

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

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.

C# Operator Overloading Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.