Skip to content

Commit 42bcae7

Browse files
BillWagnergewarren
andauthored
Create tutorial for compound assignment operators (#48476)
* Outline and sample * First draft completed. Write the first draft, including extracted samples. * proofread and fix warnings. * build warnings * warnings, again * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> --------- Co-authored-by: Genevieve Warren <[email protected]>
1 parent 844ae61 commit 42bcae7

File tree

7 files changed

+467
-0
lines changed

7 files changed

+467
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ ehthumbs_vista.db
4949
[Bb]in/
5050
[Oo]bj/
5151
*.sln
52+
*.slnx
5253
*.user
5354

5455
# Ionide folder, used in F# for VSCode

docs/csharp/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,8 @@ items:
174174
href: whats-new/version-update-considerations.md
175175
- name: Tutorials
176176
items:
177+
- name: Explore compound assignment
178+
href: whats-new/tutorials/compound-assignment-operators.md
177179
- name: Explore primary constructors
178180
href: whats-new/tutorials/primary-constructors.md
179181
- name: Explore static interface members
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
---
2+
title: Explore user defined instance compound assignment operators
3+
description: "C# 14 enables user defined instance compound assignment operators. These operators can provide better performance by minimizing allocations or copy operations. Learn how to create these operators."
4+
author: billwagner
5+
ms.author: wiwagn
6+
ms.service: dotnet-csharp
7+
ms.topic: tutorial
8+
ms.date: 09/15/2025
9+
ai-usage: ai-assisted
10+
#customer intent: As a C# developer, I want implement user defined instance compound assignment operators so that my algorithms are more efficient.
11+
---
12+
# Tutorial: Create compound assignment operators
13+
14+
C#14.0 adds *user defined compound assignment operators* that enable mutating a data structure in place, rather than creating a new instance. In previous versions of C#, the expression:
15+
16+
```csharp
17+
a += b;
18+
```
19+
20+
Was expanded to the following code:
21+
22+
```csharp
23+
var tmp = a + b;
24+
a = tmp;
25+
```
26+
27+
Depending on the type of `a`, this expansion leads to excessive allocations to create new instances, or copying the values of several properties to set values on the copy. Adding a user defined operator for `+=` indicates a type can do a better job by updating the destination object in place.
28+
29+
C# supports the existing expansion, but it uses it only when a compound user defined operator isn't available.
30+
31+
In this tutorial, you:
32+
33+
> [!div class="checklist"]
34+
>
35+
> * Install prerequisites
36+
> * Analyze the starting sample
37+
> * Implement compound assignment operators
38+
> * Analyze completed sample
39+
40+
## Prerequisites
41+
42+
- The .NET 10 preview SDK. Download it from the [.NET download site](https://dotnet.microsoft.com/download/dotnet/10.0).
43+
- Visual Studio 2026 (preview). Download it from the [Visual Studio insiders page](https://visualstudio.microsoft.com/insiders/).
44+
45+
## Analyze the starting sample
46+
47+
Run the starter application. You can get it from [the `dotnet/docs` GitHub repository](https://github.com/dotnet/docs/blob/main/docs/csharp/whats-new/tutorials/snippets/CompoundAssignment). The sample application simulates concert attendance tracking at a theater venue. The simulation models realistic arrival patterns throughout the evening, from early attendees to the main rush before showtime. This simulation demonstrates the object allocations when using traditional operators versus the efficiency gains possible with user-defined compound assignment operators.
48+
49+
The app tracks attendance through multiple theater gates (main floor and balcony sections) as concert-goers arrive. Each gate maintains a count of attendees using a `GateAttendance` record. Throughout the simulation, the code frequently updates these counts using increment (`++`) and addition (`+=`) operations. The following code shows a portion of that simulation:
50+
51+
:::code language="csharp" source="./snippets/CompoundAssignment/GateAttendanceTests.cs" id="Simulation":::
52+
53+
With traditional operators, each operation creates a new `GateAttendance` instance due to the immutable nature of records, leading to significant memory allocations.
54+
55+
When you run the simulation, you see detailed output showing:
56+
57+
- Gate-by-gate attendance numbers during different arrival periods.
58+
- Total attendance tracking across all gates.
59+
- A final comprehensive report with attendance statistics.
60+
61+
You can see a portion of the output:
62+
63+
```txt
64+
Peak arrival time - all gates busy...
65+
66+
Peak rush period completed - all gates processed heavy traffic.
67+
68+
--- Gate Status After Main Rush (7:15 PM) ---
69+
Main Floor Gates:
70+
Main-Floor-Gate-1: 145 attendees
71+
Main-Floor-Gate-2: 168 attendees
72+
Main-Floor-Gate-3: 149 attendees
73+
Main-Floor-Gate-4: 71 attendees
74+
Main Floor Subtotal: 533 attendees
75+
76+
Balcony Gates:
77+
Balcony-Gate-Left: 164 attendees
78+
Balcony-Gate-Right: 134 attendees
79+
Balcony Subtotal: 298 attendees
80+
81+
Total Current Attendance: 831 / 1000
82+
83+
--- Late Arrivals (7:15 PM - 7:30 PM) ---
84+
Final patrons arriving before curtain...
85+
86+
Final arrivals processed - concert about to begin!
87+
```
88+
89+
Examine the starter `GateAttendance` record class:
90+
91+
:::code language="csharp" source="./snippets/CompoundAssignment/GateAttendance.cs" id="GateAttendanceStarter":::
92+
93+
The `InitialImplementation.GateAttendance` record demonstrates the traditional approach to operator overloading in C#. Notice how both the increment operator (`++`) and addition operator (`+`) create entirely new instances of `GateAttendance` using the `with` expression. Each time you write `gate++` or `gate += partySize`, the operators allocate a new record instance with the updated `Count` value, then return that new instance. While this approach maintains immutability and thread safety, it comes at the cost of frequent memory allocations. In scenarios with many operations—like the concert simulation with hundreds of attendance updates—these allocations accumulate quickly, potentially impacting performance and increasing garbage collection pressure.
94+
95+
To see this allocation behavior in action, try running the [.NET Object Allocation tracking tool](/visualstudio/profiling/dotnet-alloc-tool) in Visual Studio. When you profile the current implementation during the concert simulation, you discover that it allocates 134 `GateAttendance` objects to complete the relatively small simulation. Each operator call creates a new instance, demonstrating how quickly allocations can accumulate in real-world scenarios. This measurement provides a concrete baseline for comparing the performance improvements you achieve with compound assignment operators.
96+
97+
## Implement compound assignment operators
98+
99+
C# 14 introduces user-defined compound assignment operators that enable in-place mutations instead of creating new instances. These operators provide a more efficient alternative to the traditional pattern while maintaining the familiar compound assignment syntax.
100+
101+
Compound assignment operators use a new syntax that declares `void` return methods with the `operator` keyword. Add the following operators to the `GateAttendance` class:
102+
103+
```csharp
104+
public void operator +=(int value) => this.property += value;
105+
public void operator ++() => this.property++;
106+
```
107+
108+
The key differences from traditional operators are:
109+
110+
- **Mutation**: They modify the current instance directly using `this`.
111+
- **No new instances**: Unlike traditional operators that return new objects, compound operators modify existing ones.
112+
- **Return type**: Compound assignment operators return `void`, not the type itself.
113+
114+
When the compiler encounters compound assignment expressions like `a += b` or `++a`, it follows this resolution order:
115+
116+
1. **Check for compound assignment operator**: If the type defines a user-defined compound assignment operator (for example, `+=` or `++`), use it directly.
117+
2. **Fallback to traditional expansion**: If no compound operator exists, expand to the traditional form (`a = a + b`).
118+
119+
This means you can implement both approaches simultaneously. The compound operators take precedence when available, but the traditional operators serve as fallbacks for scenarios where compound assignment isn't suitable.
120+
121+
Compound assignment operators provide several advantages:
122+
123+
- **Reduced allocations**: Modify objects in-place instead of creating new instances.
124+
- **Improved performance**: Eliminate temporary object creation and reduce garbage collection pressure.
125+
- **Familiar syntax**: Use the same `+=`, `++` syntax developers already know.
126+
- **Backward compatibility**: Traditional operators continue to work as fallbacks.
127+
128+
The new compound assignment operators are shown in the following code:
129+
130+
:::code language="csharp" source="./snippets/CompoundAssignment/GateAttendance.cs" id="CompoundAssignmentOperators":::
131+
132+
## Analyze finished sample
133+
134+
Now that you implemented the compound assignment operators, it's time to measure the performance improvement. To see the dramatic difference in memory allocations, run the [.NET Object Allocation tracking tool](/visualstudio/profiling/dotnet-alloc-tool) again on the updated code.
135+
136+
When you profile the application with the compound assignment operators enabled, you observe a remarkable reduction: only **10 `GateAttendance` objects** are allocated during the entire concert simulation, compared to the previous 134 allocations. This update represents a 92% reduction in object allocations!
137+
138+
The remaining 10 allocations come from the initial creation of the `GateAttendance` instances for each theater gate (four main floor gates + two balcony gates = six initial instances), plus a few more allocations from other parts of the simulation that don't use the compound operators.
139+
140+
This allocation reduction translates to real performance benefits:
141+
142+
- **Reduced memory pressure**: Less frequent garbage collection cycles.
143+
- **Better cache locality**: Fewer object creations mean less memory fragmentation.
144+
- **Improved throughput**: CPU cycles saved from allocation and collection overhead.
145+
- **Scalability**: Benefits multiply in scenarios with higher operation volumes.
146+
147+
The performance improvement becomes even more significant in production applications where similar patterns occur at much larger scales—imagine tracking millions of transactions, updating thousands of counters, or processing high-frequency data streams.
148+
149+
Try identifying other opportunities for compound assignment operators in the codebase. Look for patterns where you see traditional assignment operations like `gates.MainFloorGates[1] = gates.MainFloorGates[1] + 4` and consider whether they could benefit from compound assignment syntax. While some of these operations are already using `+=` in the simulation code, the principle applies to any scenario where you repeatedly modify objects rather than creating new instances.
150+
151+
As a final experiment, change the `GateAttendance` type from a `record class` to a `record struct`. It's a different optimization, and it works in this simulation because the struct has a small memory footprint. Copying a `GateAttendance` struct isn't an expensive operation. Even so, you see small improvements.
152+
153+
## Related content
154+
155+
- [What's new in C# 14](../csharp-14.md)
156+
- [Operator overloading - define unary, arithmetic, equality, and comparison operators](../../language-reference/operators/operator-overloading.md)
157+
- [Analyze memory usage by using the .NET Object Allocation tool - Visual Studio](/visualstudio/profiling/dotnet-alloc-tool)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net10.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
<LangVersion>preview</LangVersion>
9+
</PropertyGroup>
10+
11+
</Project>
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// <GateAttendanceStarter>
2+
public record class GateAttendance(string GateId)
3+
{
4+
public int Count { get; init; }
5+
6+
public static GateAttendance operator ++(GateAttendance gate)
7+
{
8+
GateAttendance updateGate = gate with { Count = gate.Count + 1 };
9+
return updateGate;
10+
}
11+
12+
public static GateAttendance operator +(GateAttendance gate, int partySize)
13+
{
14+
GateAttendance updateGate = gate with { Count = gate.Count + partySize };
15+
return updateGate;
16+
}
17+
}
18+
// </GateAttendanceStarter>
19+
20+
namespace FinalImplementation
21+
{
22+
public record class GateAttendance(string GateId)
23+
{
24+
public int Count { get; private set; }
25+
26+
public static GateAttendance operator ++(GateAttendance gate)
27+
{
28+
GateAttendance updateGate = gate with { Count = gate.Count + 1 };
29+
return updateGate;
30+
}
31+
32+
public static GateAttendance operator +(GateAttendance gate, int partySize)
33+
{
34+
GateAttendance updateGate = gate with { Count = gate.Count + partySize };
35+
return updateGate;
36+
}
37+
38+
// <CompoundAssignmentOperators>
39+
public void operator ++() => Count++;
40+
41+
public void operator +=(int partySize) => Count += partySize;
42+
// </CompoundAssignmentOperators>
43+
}
44+
}

0 commit comments

Comments
 (0)