C# Arithmetic Assignment Operator

In this chapter you will learn:

  1. What are the assignment operator
  2. Example to use the assignment operators

Description

C# Assignment Operator has this general form:

var = expression;

The general form of the shorthand is

var op = expression;

Thus, the arithmetic and logical assignment operators are

  • +=
  • -=
  • *=
  • /=
  • %=
  • &=
  • |=
  • ^=

Full list of shortcut assignment operators available in C#.


Shortcut Operator                 Equivalent To
//from  w w  w . j av a  2 s  .co m
x++, ++x                          x=x+1

x--, --x                          x=x-1

x+=y                              x=x+y

x-=y                              x=x-y

x*=y                              x=x*y

x/=y                              x=x/y

x%=y                              x=x%y

x>>= y                            x=x>>y

x<<= y                            x=x<<y

x&=y                              x=x&y

x|=y                              x=x|y

x^=y                              x=x^y 

Example


using System;/*from  www.ja va 2 s  . c om*/

class MainClass
{
  static void Main(string[] args)
  {
    int a, b, c, d, e;

    a = 1;
    a += 1;
    Console.WriteLine(a);
    b = a;
    b -= 2;
    Console.WriteLine(b);
    c = b;
    c *= 3;
    Console.WriteLine(c);
    d = 4;
    d /= 2;
    Console.WriteLine(d);
    e = 23;
    e %= 3;
    Console.WriteLine(e);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What are C# Increment and Decrement Operators
  2. How to use C# Increment and Decrement Operators
  3. Example for C# Increment and Decrement Operators
Home »
  C# Tutorial »
    C# Language »
      C# Operators
C# Arithmetic Operators
C# Arithmetic Assignment Operator
C# Increment and Decrement Operators
C# Remainder operator
C# Relational operators
C# Conditional Operators
C# Ternary operator(The ? Operator)
C# Bitwise Operators
C# Bitwise Shift Operators
C# sizeof Operator
C# typeof Operator