C# Unary Operators (Increment and Decrement)

Unary Operators are the Increment and Decrement Operators. They operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1.

  • Post-Increment or Post-Decrement:
    First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
  • Pre-Increment Pre-Decrement:
    Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.

Example of Unary Operators in C#

using System;

namespace Operator
{
   class Unary
   {
      public static void Main(string[] args)
      {
         int num = 10, result;

         result = ++num;
         Console.WriteLine("'++num' Result: {0}", result);

         result = --num;
         Console.WriteLine("'--num' Result: {0}", result);

      }
   }
}

Output:

'++num' Result: 11
'--num' Result: 10

Example of Post and Pre Increment operators in C#

using System;

namespace Operator
{
   class Unary
   {
      public static void Main(string[] args)
      {
         int num = 10;

         Console.WriteLine("Post and Pre INCREMENT");
         Console.WriteLine((num++));
         Console.WriteLine((num));

         Console.WriteLine((++num));
         Console.WriteLine((num));

         Console.WriteLine("Post and Pre DECREMENT");
         num = 10;
         Console.WriteLine((num--));
         Console.WriteLine((num));

         Console.WriteLine((--num));
         Console.WriteLine((num));
      }
   }
}

Output:

Post and Pre INCREMENT
10
11
12
12
Post and Pre DECREMENT
10
9
8
8