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#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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:
1 2 | '++num' Result: 11 '--num' Result: 10 |
Example of Post and Pre Increment operators in C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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:
1 2 3 4 5 6 7 8 9 10 | Post and Pre INCREMENT 10 11 12 12 Post and Pre DECREMENT 10 9 8 8 |