Compound assignment operators in C#

CsharpProgrammingServer Side Programming

A compound assignment operator has a shorter syntax to assign the result. The operation is performed on the two operands before the result is assigned to the first operand.

The following are the compound assignment operators in C#.

Sr.NoOperator & Operator Name
1+=
Addition Assignment
2-=
Subtraction Assignment
3*=
Multiplication Assignment
4/=
Division Assignment
5%=
Modulo Assignment
6&=
Bitwise AND Assignment
7|=
Bitwise OR Assignment
8^=
Bitwise XOR Assignment
9<<=
Left Shift Assignment
10>>=
Right Shift Assignment
11=>
Lambda Operator

Let us see an example to learn how to work with compound assignment operators in C#.

Example

 Live Demo

using System;
namespace Program {
   class MyClass {
      public static void Main(string[] args) {
         int val = 7;
         val += 3;
         Console.WriteLine("Addition Assignment: " + val);
         val -= 2;
         Console.WriteLine("Subtraction Assignment: " + val);
         val *= 7;
         Console.WriteLine("Multiplication Assignment: " + val);
         val /= 7;
         Console.WriteLine("Division Assignment: " + val);
         val %= 5;
         Console.WriteLine("Modulo Assignment: " + val);
         val &= 9;
         Console.WriteLine("Bitwise And Assignment: " + val);
         val <<= 3;
         Console.WriteLine("Left Shift Assignment: " + val);
         val >>= 5;
         Console.WriteLine("Right Shift Assignment: " + val);
      }
   }
}

Output

Addition Assignment: 10
Subtraction Assignment: 8
Multiplication Assignment: 56
Division Assignment: 8
Modulo Assignment: 3
Bitwise And Assignment: 1
Left Shift Assignment: 8
Right Shift Assignment: 0
raja
Published on 17-Sep-2018 11:39:26
Advertisements