Assignment Operators in C#

Assignment operators are used for assigning a value to a variable. In C# the assignment operator is the equal sign (=). It’s often used as a suffix in combination with an arithmetic operator to perform an operation on an existing variable (typically used as the left operand) and assign the result to itself. These operators are also known as compound assignment operators.

If you aren’t generally familiar with operators and precedence in programming, then I suggest that you check out my blog post on Working with Operators in C#.

There are assignment operators for each bitwise operator. Here are the assignment operators used in C#:

Operand Description
= Assignment operator. Assigns the value of the operand on the right to the variable on the left.
+= Compound addition operator. Adds the right operand to the left and assigns the result to the left variable.
-= Compound subtraction operator. Subtracts the right operand to the left and assigns the result to the left variable.
*= Compound multiplication operator. Multiplies the right operand by the left and assigns the result to the left variable.
/= Compound division operator. Divides the right operand by the left and assigns the result to the left variable.
%= Compound modulus operator. Divides the right operand by the left to find the remainder and assign the result to the left variable.
&= Compound AND operator. Performs the bitwise AND operation on numerical operands and the logical AND operation on boolean operands.
|= Compound OR operator. Performs the bitwise OR operation on numerical operands and the logical OR operation on boolean operands.
^= Compound XOR operator. Performs the bitwise XOR operation on numerical operands and the logical XOR operation on boolean operands.
<<= Compound left shift operator. Shifts the left operand to the left by the value in the right operand.
>>= Compound right shift operator. Shifts the left operand to the right by the value in the right operand.

Example using assignment operators

int x = 5;
int y = 10;

x += 5;
Console.WriteLine(x);   // Output: 10

y -= 5;
Console.WriteLine(y);  // Output: 5

x *= y;
Console.WriteLine(x);  // Output: 50
comments powered by Disqus