You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/csharp/whats-new/tutorials/compound-assignment-operators.md
+17-19Lines changed: 17 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,14 @@
1
1
---
2
2
title: Explore user defined instance compound assignment operators
3
-
description: "C# 14 enables user defined instance compound assignment operators. These can provide better performance by minimizing allocations or copy operations. Learn how to create these 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
4
author: billwagner
5
5
ms.author: wiwagn
6
6
ms.service: dotnet-csharp
7
7
ms.topic: tutorial
8
8
ms.date: 09/15/2025
9
-
9
+
ai-usage:ai-assisted
10
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
11
---
13
-
14
12
# Tutorial: Create compound assignment operators
15
13
16
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:
@@ -19,16 +17,16 @@ C#14.0 adds *user defined compound assignment operators* that enable mutating a
19
17
a+=b;
20
18
```
21
19
22
-
was expanded to the following code:
20
+
Was expanded to the following code:
23
21
24
22
```csharp
25
23
vartmp=a+b;
26
24
a=tmp;
27
25
```
28
26
29
-
Depending on the type of `a`, this 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.
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.
30
28
31
-
C# still supports the existing expansion, but it uses it only when a compound user defined operator isn't available.
29
+
C# supports the existing expansion, but it uses it only when a compound user defined operator isn't available.
32
30
33
31
In this tutorial, you:
34
32
@@ -45,15 +43,15 @@ In this tutorial, you:
45
43
46
44
## Analyze the starting sample
47
45
48
-
Run the app to understand what it does. The sample application simulates concert attendance tracking at a theater venue. The simulation models realistic arrival patterns throughout the evening, from early patrons to the main rush before showtime. This simulation demonstrates the performance impact of object allocations when using traditional operators versus the efficiency gains possible with user-defined compound assignment operators.
46
+
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.
49
47
50
48
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:
With traditional operators, each operation creates a new `GateAttendance` instance due to the immutable nature of records, leading to significant memory allocations.
55
53
56
-
When you run the simulation, you'll see detailed output showing:
54
+
When you run the simulation, you see detailed output showing:
57
55
58
56
- Gate-by-gate attendance numbers during different arrival periods.
59
57
- Total attendance tracking across all gates.
@@ -95,13 +93,13 @@ Examine the starter `GateAttendance` record class:
95
93
96
94
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 our concert simulation with hundreds of attendance updates—these allocations accumulate quickly, potentially impacting performance and increasing garbage collection pressure.
97
95
98
-
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'll 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'll achieve with compound assignment operators.
96
+
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.
99
97
100
98
## Implement compound assignment operators
101
99
102
100
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.
103
101
104
-
Compound assignment operators use a new syntax that declares `void` return methods with the `operator` keyword:
102
+
Compound assignment operators use a new syntax that declares `void` return methods with the `operator` keyword. Add the following operators to the `GateAttendance` class:
@@ -110,9 +108,9 @@ public void operator ++() => this.property++;
110
108
111
109
The key differences from traditional operators are:
112
110
113
-
-**Return type**: Compound assignment operators return `void`, not the type itself
114
111
-**Mutation**: They modify the current instance directly using `this`
115
112
-**No new instances**: Unlike traditional operators that return new objects, compound operators modify existing ones
113
+
-**Return type**: Compound assignment operators return `void`, not the type itself
116
114
117
115
When the compiler encounters compound assignment expressions like `a += b` or `++a`, it follows this resolution order:
118
116
@@ -134,11 +132,11 @@ The new compound assignment operators are shown in the following code:
134
132
135
133
## Analyze finished sample
136
134
137
-
Now that you've implemented the compound assignment operators, it's time to measure the performance improvement. Run the [.NET Object Allocation tracking tool](~/visualstudio/profiling/dotnet-alloc-tool) again on the updated code to see the dramatic difference in memory allocations.
135
+
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.
138
136
139
-
When you profile the application with the compound assignment operators enabled, you'll observe a remarkable reduction: only **10 `GateAttendance` objects** are allocated during the entire concert simulation, compared to the previous 134 allocations. This represents a 92% reduction in object allocations!
137
+
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!
140
138
141
-
The remaining 10 allocations come from the initial creation of the `GateAttendance` instances for each theater gate (4 main floor gates + 2 balcony gates = 6 initial instances), plus a few additional allocations from other parts of the simulation that don't use the compound operators.
139
+
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.
142
140
143
141
This allocation reduction translates to real performance benefits:
144
142
@@ -149,12 +147,12 @@ This allocation reduction translates to real performance benefits:
149
147
150
148
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.
151
149
152
-
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 are already using `+=` in the simulation code, the principle applies to any scenario where you're repeatedly modifying objects rather than creating new instances.
150
+
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're repeatedly modifying objects rather than creating new instances.
153
151
154
-
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'll see small improvements.
152
+
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.
155
153
156
154
## Related content
157
155
158
156
-[What's new in C# 14](../csharp-14.md)
159
-
-[Operator overloading - define unary, arithmetic, equality and comparison operators](../../language-reference/operators/operator-overloading.md)
160
-
-[Analyze memory usage by using the .NET Object Allocation tool - Visual Studio](~/visualstudio/profiling/dotnet-alloc-tool)
157
+
-[Operator overloading - define unary, arithmetic, equality, and comparison operators](../../language-reference/operators/operator-overloading.md)
158
+
-[Analyze memory usage by using the .NET Object Allocation tool - Visual Studio](/visualstudio/profiling/dotnet-alloc-tool)
0 commit comments