C# program to overload Unary Increment (++) and Decrement (--) operators

Overloading ++ and -- in C#: Here, we are going to learn how to overload Unary Increment (++) and Unary Decrement (--) Operators in C#?
Submitted by IncludeHelp, on October 04, 2019

Problem statement

Write a C# program to overload Unary Increment (++) and Decrement (--) operators.

C# program to overload Unary Increment (++) and Decrement (--) operators

Here, we will design overloaded methods for unary increment (++) and decrement (--). In the below program, we will create a class Sample, with data member val.

using System;

namespace ConsoleApplication1
{
    class Sample
    {
        //declare integer data member
        private int val;
        
        //initialize data members
        public Sample(int val)
        {
            this.val = val;
        }

        //Overload unary decrement operator
        public static Sample operator --(Sample S)
        {
            S.val = --S.val;
            return S;
        }

        //Overload unary increment operator
        public static Sample operator ++(Sample S)
        {
            S.val = ++S.val;
            return S;
        }

        public void PrintValues()
        {
            Console.WriteLine("Values of val: " + val);
            Console.WriteLine();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Sample S = new Sample(10);

            S++;
            S++;
            S++;
            S.PrintValues();

            S--;
            S--;
            S.PrintValues();
        }
    }
}

Output

Values of val: 13

Values of val: 11

C# Operator Overloading Programs »

Comments and Discussions!

Load comments ↻





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