C# Prefix and Postfix Operators

Updated on     Kisan Patel

Both the ++ and — operators can be used as prefix or postfix operators.

1. Prefix Form

num1 = 3;
num2 = ++num1; // num1 = 4, num2 = 4

In prefix form, the compiler will first increment num1 by 1 and then will assign it to num2.

2. Postfix Form

num1 = 3;
num2 = num1++; // num2 = 3, num1 = 4

In postfix form, the compiler will first assign num1 to num2 and then increment num1 by 1.

More C# Examples

num1 = 5;
num2 = --num1; // num2 = 4, num1 = 4
num1 = 5;
num2 = num1--; // num2 = 5, num1 = 4
using System;

namespace VariableDemo
{
    class OperatorDemo
    {
        static void Main(string[] args)
        {
            int a = 5, b, c;
            b = a++ + 3;
            c = --a;

            Console.WriteLine("The value of a is " + a);
            Console.WriteLine("The value of b is " + b);
            Console.WriteLine("The value of c is " + c);
        }
    }
}

Output of the above C# program…

c-sharp-postfix-prefix-operator-demo


C#

Leave a Reply