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

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




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.