C# - Assignment Operators
C# - Assignment Operators
Section titled “C# - Assignment Operators”In C#, assignment operators are used to assign a value to a variable. The most basic operator is the simple assignment (=). C# also provides a set of compound assignment operators that combine an arithmetic or bitwise operation with an assignment, offering a more concise syntax.
List of Assignment Operators
Section titled “List of Assignment Operators”The following table lists the assignment operators available in C#.
| Operator | Example | Equivalent to |
|---|---|---|
Simple Assignment (=) | x = y | x = y |
Add and Assign (+=) | x += y | x = x + y |
Subtract and Assign (-=) | x -= y | x = x - y |
Multiply and Assign (*=) | x *= y | x = x * y |
Divide and Assign (/=) | x /= y | x = x / y |
Modulus and Assign (%=) | x %= y | x = x % y |
Bitwise AND and Assign (&=) | x &= y | x = x & y |
Bitwise OR and Assign (|=) | x |= y | x = x | y |
Bitwise XOR and Assign (^=) | x ^= y | x = x ^ y |
Left Shift and Assign (<<=) | x <<= y | x = x << y |
Right Shift and Assign (>>=) | x >>= y | x = x >> y |
Null-Coalescing and Assign (??=) | x ??= y | if (x == null) x = y; |
Examples of Common Assignment Operators
Section titled “Examples of Common Assignment Operators”Let’s explore the most frequently used operators with clear, modern code examples.
using System;
// 1. Simple Assignment (=)int score = 100;Console.WriteLine($"Initial score: {score}");
// 2. Add and Assign (+=)score += 50; // Player earned 50 pointsConsole.WriteLine($"Score after adding points: {score}"); // 150
// 3. Subtract and Assign (-=)int health = 100;health -= 25; // Player took 25 damageConsole.WriteLine($"Health after taking damage: {health}"); // 75
// 4. Multiply and Assign (*=)double investment = 1000.0;investment *= 1.05; // Investment grew by 5%Console.WriteLine($"Investment value after growth: {investment:C}"); // $1,050.00
// 5. Divide and Assign (/=)int totalItems = 100;totalItems /= 2; // Half of the items were soldConsole.WriteLine($"Remaining items: {totalItems}"); // 50
// 6. Modulus and Assign (%=)int itemIndex = 12;int itemsPerPage = 10;itemIndex %= itemsPerPage; // Get the index on the current pageConsole.WriteLine($"Item index on page: {itemIndex}"); // 2The Null-Coalescing Assignment Operator (??=)
Section titled “The Null-Coalescing Assignment Operator (??=)”Introduced in C# 8.0, the ??= operator provides a concise way to assign a value to a variable only if that variable is null. This is extremely useful for lazy initialization and setting default values.
Example 1: Setting a Default Value
Section titled “Example 1: Setting a Default Value”using System;using System.Collections.Generic;
List<string>? names = null;
// If 'names' is null, create a new list and assign it.// If it's not null, this line does nothing.names ??= new List<string>();
names.Add("Alice");Console.WriteLine($"List contains: {string.Join(", ", names)}");Example 2: Lazy Initialization in a Class
Section titled “Example 2: Lazy Initialization in a Class”This pattern is great for performance, as the expensive object creation only happens the first time it’s needed.
public class ExpensiveService{ public ExpensiveService() { Console.WriteLine("--> ExpensiveService instance created."); }}
public class ServiceProvider{ private ExpensiveService? _service;
public ExpensiveService GetService() { // The service is only instantiated on the first call to GetService(). _service ??= new ExpensiveService(); return _service; }}
// --- Usage ---var provider = new ServiceProvider();Console.WriteLine("Provider created. Service not yet initialized.");
var s1 = provider.GetService(); // "--> ExpensiveService instance created." is printed herevar s2 = provider.GetService(); // Nothing is printed, the existing instance is returnedBest Practices and Things to Watch Out For
Section titled “Best Practices and Things to Watch Out For”- Clarity and Conciseness: Use compound assignment operators like
+=and-=to make your code more readable and concise, especially for incrementing counters or accumulating values. - Type Safety: Be aware of implicit type conversions. For example, if you divide an integer by an integer using
/=, the result will be an integer, and any fractional part will be discarded.int x = 5; x /= 2;results inxbeing2. - Division by Zero: Before using
/=or%=, ensure the right-hand operand is not zero to avoid aDivideByZeroException. - Operator Precedence: Remember that assignment operators have a very low precedence. In complex expressions, they are evaluated last. Use parentheses to ensure the order of operations is what you intend.
- Use
??=for Defaults: Embrace the??=operator for setting default values and for lazy initialization. It’s more expressive and less error-prone than anif (x == null)check.