C# Unary Operators

In this chapter you will learn:
  • What is C# Unary Operator?
  • How many types of Unary Operators in C sharp?
  • How to use unary operators in a program?

The C# unary operator is widely used for increment or decrement value by 1. This operator widely used with loop constructs to increment loop by 1. It is very easy to use and understand C# unary operators. A complete detail about this operator is given below with the complete example.

++ Increment Operator:

This operator is pronounced as increment operator. It is used for incrementing value by 1. It is used in C# programming by two types: Pre-increment (++i) and Post-increment (i++). In pre-increment, first it increments by 1 then loop executes whereas in Post-increment, the loop executes then it increments by 1.

 

You will learn more about loop in Loop Constructs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace run_csharp_code
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0; // initialization

            i++; // i incremented by one. It is post increment

            Console.WriteLine("The value of i is {0}", i);

            Console.ReadLine();
        }
    }
}

Output

The value of i is 0
Now the value of i is 1
__

-- Decrement Operator:

The behavior of decrement operator is just opposite from increment operator. It is used for decrementing the value by one. It has also two types: Pre-Decrement (--i) and Post Decrement (i--). In pre-decrement the value is decremented by one then loop executes whereas in post-decrement the loop executed then the value decrements by one.

Examples:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Decrement_Operator
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 5; // Initialization
            Console.WriteLine("The Value of i is {0}", i);

            i--; // i decremented by one. It is post-decrement

            Console.WriteLine("\nNow the value of i is {0}", i);

            Console.ReadLine();
        }
    }
}

Output

The Value of i is 5
Now the value of i is 4
__

Note: i++ or i-- has not a constant value. It is just an example using for explaining unary operator more clearly.

Summary

In this chapter, you learned about Unary Operators in C#. You also learned about increment operator and decrement operator that is types of unary operator. You saw how to use these unary operators in program. In next chapter, you will learn about different kind of Comparison operators in C#.

More Articles

 

Share your thought