Skip to content

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.

The following table lists the assignment operators available in C#.

OperatorExampleEquivalent to
Simple Assignment (=)x = yx = y
Add and Assign (+=)x += yx = x + y
Subtract and Assign (-=)x -= yx = x - y
Multiply and Assign (*=)x *= yx = x * y
Divide and Assign (/=)x /= yx = x / y
Modulus and Assign (%=)x %= yx = x % y
Bitwise AND and Assign (&=)x &= yx = x & y
Bitwise OR and Assign (|=)x |= yx = x | y
Bitwise XOR and Assign (^=)x ^= yx = x ^ y
Left Shift and Assign (<<=)x <<= yx = x << y
Right Shift and Assign (>>=)x >>= yx = x >> y
Null-Coalescing and Assign (??=)x ??= yif (x == null) x = y;

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 points
Console.WriteLine($"Score after adding points: {score}"); // 150
// 3. Subtract and Assign (-=)
int health = 100;
health -= 25; // Player took 25 damage
Console.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 sold
Console.WriteLine($"Remaining items: {totalItems}"); // 50
// 6. Modulus and Assign (%=)
int itemIndex = 12;
int itemsPerPage = 10;
itemIndex %= itemsPerPage; // Get the index on the current page
Console.WriteLine($"Item index on page: {itemIndex}"); // 2

The 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.

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)}");

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 here
var s2 = provider.GetService(); // Nothing is printed, the existing instance is returned

Best 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 in x being 2.
  • Division by Zero: Before using /= or %=, ensure the right-hand operand is not zero to avoid a DivideByZeroException.
  • 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 an if (x == null) check.