Overloading Unary Operators Example in C# (Sharp)

The following code snippet shows the overloading of – operator:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication14
{
    class calculator
    {
        public int number1, number2;
       
        public calculator( int num1, int num2)
        {
            number1=num1;
            number2=num2;
        }
        public static calculator operator -(calculator c1)
        {
            c1.number1= -c1.number1;
            c1.number2= -c1.number2;
            return c1;
        }
        public void print()
        {
            Console.WriteLine(“number1=” + number1);
            Console.WriteLine(“number 2=” + number2);
            Console.ReadLine();
        }
    }  class entrypoint
    {
        public static void Main(string [] args)
        {
            calculator calc= new calculator (15, -25);
            calc = -calc;
            calc.print();
        }
    }
}

Add Comment