In c#, Assignment Operators are useful to assign a new value to the operand, and these operators will work with only one operand.
For example, we can declare and assign a value to the variable using the assignment operator (=) like as shown below.
If you observe the above sample, we defined a variable called “a” and assigned a new value using an assignment operator (=) based on our requirements.
The following table lists the different types of operators available in c# assignment operators.
Operator | Name | Description | Example |
---|---|---|---|
= | Equal to | It is used to assign the values to variables. | int a; a = 10 |
+= | Addition Assignment | It performs the addition of left and right operands and assigns a result to the left operand. | a += 10 is equals to a = a + 10 |
-= | Subtraction Assignment | It performs the subtraction of left and right operands and assigns a result to the left operand. | a -= 10 is equals to a = a - 10 |
*= | Multiplication Assignment | It performs the multiplication of left and right operands and assigns a result to the left operand. | a *= 10 is equals to a = a * 10 |
/= | Division Assignment | It performs the division of left and right operands and assigns a result to the left operand. | a /= 10 is equals to a = a / 10 |
%= | Modulo Assignment | It performs the modulo operation on two operands and assigns a result to the left operand. | a %= 10 is equals to a = a % 10 |
&= | Bitwise AND Assignment | It performs the Bitwise AND operation on two operands and assigns a result to the left operand. | a &= 10 is equals to a = a & 10 |
|= | Bitwise OR Assignment | It performs the Bitwise OR operation on two operands and assigns a result to the left operand. | a |= 10 is equals to a = a | 10 |
^= | Bitwise Exclusive OR Assignment | It performs the Bitwise XOR operation on two operands and assigns a result to the left operand. | a ^= 10 is equals to a = a ^ 10 |
>>= | Right Shift Assignment | It moves the left operand bit values to the right based on the number of positions specified by the second operand. | a >>= 2 is equals to a = a >> 2 |
<<= | Left Shift Assignment | It moves the left operand bit values to the left based on the number of positions specified by the second operand. | a <<= 2 is equals to a = a << 2 |
Following is the example of using assignment Operators in the c# programming language.
If you observe the above example, we defined a variable or operand “x” and assigning new values to that variable by using assignment operators in the c# programming language.
When we execute the above c# program, we will get the result as shown below.
This is how we can use assignment operators in c# to assign new values to the variable based on our requirements.