C# Unary Operators

The C# Unary operators are also called increment and decrement operators. These C# unary operators generally used in the loop concepts. 

The C# Increment Operators are of two types: pre-increment(++i) and post-increment(i++). And the C# Decrement Operators are also of two types: post-decrement(i–) and pre-decrement(–i).

Generally, the difference in C# post-increment (or post-decrement) and pre-increment (or pre-decrement) shall identify while using looping concepts. When we use post-increment and post-decrement, first, the entire loop will execute. And then, the value is incremented or decremented accordingly.

In the case of pre-increment and pre-decrement, first, the value will be incremented or decremented before the loop gets executed.

Unary OperatorsOperationExample
++Increment Operator15++ is 16, ++15 is 16
Decrement Operator16– is 15, –16 is 15

C# Unary Operators Example

The following example helps you understand the C# Increment and Decrement Operators functionality.

using System;
 
 class Unary_Operators
 {
     static void Main()
     {
         int x = 15;
         int result;
 
         Console.WriteLine("x is " + x);
         result = x++;
         Console.WriteLine("Post increment of x is " + x);
 
         Console.WriteLine("x is " + x);
         result = x--;
         Console.WriteLine("Post decrement of x is " + x);
 
         Console.WriteLine("x is " + x);
         result = ++x;
         Console.WriteLine("Pre increment of x is " + x);
 
         Console.WriteLine("x is " + x);
         result = --x;
         Console.WriteLine("Pre decrement of x is " + x);
     }
 }

OUTPUT

C# Unary Operators 1

ANALYSIS

x=15 -> x++ = 16 i.e., x++ will increment it’s value 15 by 1 which results in 16 

x=16 -> x– = 15 i.e., x– will increment i’s value 16 by 1. And the C# results is 15.

Categories C#