Assignment operators in C# are used to assign values to variables. They also perform an
operation while assigning the value, such as addition, subtraction,
multiplication, division, etc..
using System;
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
// Simple assignment
int c = a;
Console.WriteLine($"c = {c}"); //
Output: c = 10
// Addition assignment
c += b;
Console.WriteLine($"c += {b} => c = {c}"); //
Output: c += 5 => c = 15
// Subtraction assignment
c -= b;
Console.WriteLine($"c -= {b} => c = {c}"); //
Output: c -= 5 => c = 10
// Multiplication assignment
c *= b;
Console.WriteLine($"c *= {b} => c = {c}"); //
Output: c *= 5 => c = 50
// Division assignment
c /= b;
Console.WriteLine($"c /= {b} => c = {c}"); //
Output: c /= 5 => c = 10
// Modulus assignment
c %= b;
Console.WriteLine($"c %= {b} => c = {c}"); //
Output: c %= 5 => c = 0
}
}
using System;
class Program
{
static void Main(string[] args)
{
int a = 5; //
Simple assignment
// Addition assignment (+=): Adds the right operand to the left
operand and assigns the result to the left operand.
int b = 10;
b += a; //
Equivalent to: b = b + a;
Console.WriteLine($"Addition Assignment: b = {b}");
// Subtraction assignment (-=): Subtracts the right operand from
the left operand and assigns the result to the left operand.
int c = 15;
c -= a; //
Equivalent to: c = c - a;
Console.WriteLine($"Subtraction Assignment: c = {c}");
// Multiplication assignment (*=): Multiplies the right operand
with the left operand and assigns the result to the left operand.
int d = 3;
d *= a; //
Equivalent to: d = d * a;
Console.WriteLine($"Multiplication Assignment: d = {d}");
// Division assignment (/=): Divides the left operand by the right
operand and assigns the result to the left operand.
int e = 20;
e /= a; //
Equivalent to: e = e / a;
Console.WriteLine($"Division Assignment: e = {e}");
// Modulus assignment (%=): Computes the modulus of the left
operand with the right operand and assigns the result to the left operand.
int f = 13;
f %= a;
// Equivalent to: f = f % a;
Console.WriteLine($"Modulus Assignment: f = {f}");
}
}
//Result
//Addition Assignment: b = 15
//Subtraction Assignment: c = 10
//Multiplication Assignment: d = 15
//Division Assignment: e = 4
//Modulus Assignment: f = 3