Code

Assignment Operators

In C#, assignment operators are used to assign a new value to a variable. This operator simply assigns whatever value is on the right to the variable on the left.

Syntax:

Compound-assignment expression such as

expression1 += expression2

is equivalent to

expression1 = expression1 + expression2

Commonly used Assignment Operators in C#

Operator Description Examples
= Assign Assign values to the left operand a = 6
+= Plus AND assign Adds right and left operand and assign the result to the left operand a += 6 means a = a + 6
-= Minus AND assign Subtracts right and left operand and assign the result to the left operand a -= 6 means a = a – 6
*= Multiply AND assign Multiplies right and left operand and assign the result to the left operand a *= 6 means a = a * 6
/= Divide AND assign Divides right and left operand and assign the result to the left operand a /= 6 means a = a / 6
%= Modulus AND assign Modulus on two operands and assign the result to the left operand a %= 6 means a = a % 6

Examples

int a, b, c;

// Syntax to initialize multiple values
a = b = c = 6;
 
Console.WriteLine(a += 1); // means a=a+1;    
Console.WriteLine(a -= 2); // means a=a-2;    
Console.WriteLine(a *= 3); // means a=a*3; 
Console.WriteLine(a /= 3); // means a=a/3;    
Console.WriteLine(a %= 3); // means a=a%3;

Run Demo

OUTPUT

7
5
15
5
2

Tagged in :

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video