What are the assignment operator

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
//  www  . ja  v  a 2 s  . c  o 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;// ww  w  . j av a2s.  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.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception