12 March 2014

Unary Operators in C#.net

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 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 loopexecutes then it increments by 1.

Examples:

using System;
 
namespace Increment_Operator
{
  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 oppositefrom 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;
 
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 

No comments:

Post a Comment