×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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 »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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