Assignment operators in C# are used to assign values to variables.
The most basic assignment operator is =, but there are several compound assignment operators that perform an operation on the variable’s current value and then assign the result back to the variable.
These operators simplify expressions and make code more concise.
In this tutorial, we’ll cover:
1. Basic Assignment Operator (=)
The = operator assigns a value to a variable. This is the simplest form of assignment in C#.
Example:
using System; public class BasicAssignment { public static void Main() { int a = 5; // Assigns the value 5 to a Console.WriteLine("a = " + a); } }
In this example:
- a = 5 assigns the integer value 5 to the variable a.
Output:
a = 5
2. Compound Assignment Operators
Compound assignment operators combine an arithmetic operation with assignment. Here’s a list of the most common compound assignment operators in C#:
Operator | Equivalent Expression | Description |
---|---|---|
+= | a = a + b | Addition assignment |
-= | a = a – b | Subtraction assignment |
*= | a = a * b | Multiplication assignment |
/= | a = a / b | Division assignment |
%= | a = a % b | Modulus assignment |
&= | a = a & b | Bitwise AND assignment |
` | =` | `a = a |
^= | a = a ^ b | Bitwise XOR assignment |
<<= | a = a << b | Left shift assignment |
>>= | a = a >> b | Right shift assignment |
3. Examples Using Compound Assignment Operators
Let’s look at some examples of compound assignment operators in action.
Example: Addition Assignment (+=)
using System; public class AdditionAssignmentExample { public static void Main() { int x = 10; x += 5; // Equivalent to x = x + 5 Console.WriteLine("x += 5: " + x); // Output: 15 } }
Example: Subtraction Assignment (-=)
using System; public class SubtractionAssignmentExample { public static void Main() { int y = 20; y -= 3; // Equivalent to y = y - 3 Console.WriteLine("y -= 3: " + y); // Output: 17 } }
Example: Multiplication Assignment (*=)
using System; public class MultiplicationAssignmentExample { public static void Main() { int z = 7; z *= 3; // Equivalent to z = z * 3 Console.WriteLine("z *= 3: " + z); // Output: 21 } }
Example: Division Assignment (/=)
using System; public class DivisionAssignmentExample { public static void Main() { int a = 20; a /= 4; // Equivalent to a = a / 4 Console.WriteLine("a /= 4: " + a); // Output: 5 } }
Example: Modulus Assignment (%=)
using System; public class ModulusAssignmentExample { public static void Main() { int b = 10; b %= 3; // Equivalent to b = b % 3 Console.WriteLine("b %= 3: " + b); // Output: 1 } }
4. Assignment with Different Data Types
Assignment operators work with different data types, including int, float, double, and string.
Example: Concatenation with Strings (+=)
The += operator can be used to concatenate strings.
using System; public class StringConcatenationExample { public static void Main() { string greeting = "Hello"; greeting += ", world!"; // Concatenates and assigns the result to greeting Console.WriteLine(greeting); // Output: Hello, world! } }
Example: Floating-Point Assignment (*=)
Compound assignment operators can also be used with floating-point numbers.
using System; public class FloatAssignmentExample { public static void Main() { float price = 19.99f; price *= 1.1f; // Increases price by 10% Console.WriteLine("New price: $" + price); // Output: New price: $21.989 } }
5. Practical Examples of Assignment Operators
Example 1: Updating a Counter with Addition Assignment (+=)
The += operator is commonly used to update counters in loops.
using System; public class CounterExample { public static void Main() { int counter = 0; for (int i = 1; i <= 5; i++) { counter += i; // Adds i to counter } Console.WriteLine("Final counter value: " + counter); // Output: 15 } }
Explanation:
- This code adds each value from 1 to 5 to the counter using the += operator, resulting in a total of 15.
Example 2: Applying a Discount with Multiplication Assignment (*=)
You can use compound assignment to apply discounts or adjustments in pricing.
using System; public class DiscountExample { public static void Main() { double price = 50.0; double discount = 0.85; // 15% off price *= discount; // Applies a 15% discount Console.WriteLine("Discounted price: $" + price); // Output: 42.5 } }
Explanation:
- The price is multiplied by discount (0.85) using *= to reduce the price by 15%.
Example 3: Adjusting Bitwise Flags with OR Assignment (|=)
Compound bitwise operators are often used to set or clear flags in binary data.
using System; public class BitwiseFlagsExample { public static void Main() { int flags = 0b_0000_0001; // Initial flag set at first bit int newFlag = 0b_0000_0100; // New flag to set at third bit flags |= newFlag; // Sets the third bit of flags Console.WriteLine("New flags: " + Convert.ToString(flags, 2)); // Output: 101 } }
Explanation:
- flags |= newFlag sets the third bit in flags without changing the existing set bits.
Example 4: Reducing Loan Amount with Subtraction Assignment (-=)
Compound operators are useful for tracking cumulative reductions, such as loan payments.
using System; public class LoanPaymentExample { public static void Main() { double loanAmount = 1000.0; double monthlyPayment = 200.0; for (int i = 0; i < 5; i++) { loanAmount -= monthlyPayment; // Reduces loan amount by monthly payment Console.WriteLine("Remaining loan after month " + (i + 1) + ": $" + loanAmount); } } }
Explanation:
- The code deducts the monthly payment from the loan amount for each of 5 months.
Output:
Remaining loan after month 1: $800 Remaining loan after month 2: $600 Remaining loan after month 3: $400 Remaining loan after month 4: $200 Remaining loan after month 5: $0
Summary
Assignment operators in C# provide a convenient way to assign and update variable values. Here’s a recap:
- Basic Assignment (=): Assigns a value to a variable.
- Compound Assignment Operators: Perform an operation and assign the result in one step, making code cleaner and more efficient.
- +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
- Using with Different Data Types: Compound operators work with int, double, string, and more.
- Practical Applications: Compound operators are useful in loops, flag setting, price adjustments, and cumulative calculations.