C Sharp/Increment and Decrement Operators

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators

C# - Flow Control
C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

[edit] C# Increment and Decrement Operators


C# increment and decrement operators are denoted by the ++ or -- symbols in front or behind the variable'


Here is a chart of how the increment and decrement operators work


C# increment and decrement operators

Name Operator X = 100 Y
Pre-increment ++X 101 101
Post-increment X++ 100 101
Pre-decrement --X 99 99
Post-decrement X-- 100 99


We will give you an example of real c# code.


Output:

using System;
 
class Program
{
    static void Main(string[] args)
    {
 
        int y;
        int a = 100;
 
        y = ++a;   //pre-increment
        Console.WriteLine("y = " + y + " and a = " + a);
        //y=101  and a=101
 
        y = a++;   //post-increment
        Console.WriteLine("y = " + y + " and a = " + a);
        //y=101  and a=102
 
        Console.Read();
    }
}


As you can see post-increment and pre-increment will always increment variable a. Post-increment will NOT change the left side of the expression which is variable y in the code above.