Unary Operators

Learn about unary operators in this lesson.

We'll cover the following...

In the previous lesson we discussed the basic operators used in C#. One of the types listed was the unary operators. Let’s learn about them now.

Unary Operators Example

Take a look at the example below which uses the unary operators.

Press + to interact
using System;
class UnaryOps
{
public static void Main()
{
int unOps = 5;
int preIncrement;
int preDecrement;
int postIncrement;
int postDecrement;
int positive;
int negative;
bool temp;
preIncrement = ++unOps;
Console.WriteLine("pre-Increment: {0}", preIncrement);
preDecrement = --unOps;
Console.WriteLine("pre-Decrement: {0}", preDecrement);
postDecrement = unOps--;
Console.WriteLine("Post-Decrement: {0}", postDecrement);
postIncrement = unOps++;
Console.WriteLine("Post-Increment: {0}", postIncrement);
Console.WriteLine("Final Value of unOps is: {0}", unOps);
positive = +postIncrement;
Console.WriteLine("Positive: {0}", positive);
negative = -postIncrement;
Console.WriteLine("Negative: {0}", negative);
temp = false;
temp = !temp;
Console.WriteLine("Logical Not: {0}", temp);
}
}

Code Explanation

When evaluating expressions:

  • postIncrement (x++) and postDecrement (x--) operators return their current value and then apply the operators.
  • preIncrement (++x) and preDecrement (--x) operators apply the operators to the variable prior to returning the final value.

In the code ...