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
* edit pass based on feedback
Fixes#49604
Also, searched for other instances of Visual Studio preview (which is now generally released) and update those as well.
* Copilot review updates
* Apply suggestions from code review
description: "C# 14 enables userdefined instance compound assignment operators. These operators can provide better performance by minimizing allocations or copy operations. Learn how to create these operators."
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
-
ms.date: 09/15/2025
8
+
ms.date: 11/14/2025
9
9
ai-usage: ai-assisted
10
-
#customer intent: As a C# developer, I want implement userdefined instance compound assignment operators so that my algorithms are more efficient.
10
+
#customer intent: As a C# developer, I want to implement user-defined instance compound assignment operators so that my algorithms are more efficient.
11
11
---
12
12
# Tutorial: Create compound assignment operators
13
13
14
-
C#14.0 adds *userdefined compound assignment operators* that enable mutating a data structure in place, rather than creating a new instance. In previous versions of C#, the expression:
14
+
C#14 adds [*user-defined compound assignment operators*](~/_csharplang/proposals/csharp-14.0/user-defined-compound-assignment.md) that enable mutating a data structure in place, rather than creating a new instance. In previous versions of C#, the expression:
15
15
16
16
```csharp
17
17
a+=b;
@@ -20,27 +20,28 @@ a += b;
20
20
Was expanded to the following code:
21
21
22
22
```csharp
23
+
// compiler-generated code prior to C# 13:
23
24
vartmp=a+b;
24
25
a=tmp;
25
26
```
26
27
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 userdefined operator for `+=` indicates a type can do a better job by updating the destination object in place.
28
+
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
29
-
C# supports the existing expansion, but it uses it only when a compound userdefined operator isn't available.
30
+
C# supports the existing expansion, but it uses it only when a compound user-defined operator isn't available.
30
31
31
32
In this tutorial, you:
32
33
33
34
> [!div class="checklist"]
34
35
>
35
-
> *Install prerequisites
36
-
> *Analyze the starting sample
37
-
> * Implement compound assignment operators
38
-
> * Analyze completed sample
36
+
> *Run the starting sample.
37
+
> *Identify bottlenecks in the code.
38
+
> * Implement new compound assignment operators.
39
+
> * Analyze the completed sample.
39
40
40
41
## Prerequisites
41
42
42
43
- The .NET 10 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
+
- Visual Studio 2026. Download it from the [Visual Studio page](https://visualstudio.microsoft.com).
44
45
45
46
## Analyze the starting sample
46
47
@@ -50,15 +51,17 @@ The app tracks attendance through multiple theater gates (main floor and balcony
With traditional operators, each operation creates a new `GateAttendance` instance due to the immutable nature of records, leading to significant memory allocations.
54
+
## Identify bottlenecks in the code
54
55
55
-
When you run the simulation, you see detailed output showing:
56
+
With traditional operators, each operation creates a new `GateAttendance` instance, leading to significant memory allocations. The starter `GateAttendance` is *immutable*. Your code can't modify the state of the object after it's been initialized. That design decision requires copying objects if you need to modify state.
57
+
58
+
When you run the simulation, the detailed output shows:
56
59
57
60
- Gate-by-gate attendance numbers during different arrival periods.
58
61
- Total attendance tracking across all gates.
59
62
- A final comprehensive report with attendance statistics.
60
63
61
-
You can see a portion of the output:
64
+
The following text displays some of the example output:
62
65
63
66
```txt
64
67
Peak arrival time - all gates busy...
@@ -92,7 +95,7 @@ Examine the starter `GateAttendance` record class:
92
95
93
96
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
97
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.
98
+
To measure this allocation behavior, 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
99
97
100
## Implement compound assignment operators
98
101
@@ -129,9 +132,12 @@ The new compound assignment operators are shown in the following code:
> Developers familiar with C++ might wonder why only one `++` or `--` operator is required. The compiler generates the code to use either the expression before or after modification as the return value. The compiler-generated code performs the assignment using either the original value or the modified value based on whether pre-increment (`++x`) or post-increment (`x++`) was called.
137
+
132
138
## Analyze finished sample
133
139
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.
140
+
Now that you implemented the compound assignment operators, it's time to measure the performance improvement. To measure the dramatic difference in memory allocations, run the [.NET Object Allocation tracking tool](/visualstudio/profiling/dotnet-alloc-tool) again on the updated code.
135
141
136
142
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
143
@@ -146,9 +152,9 @@ This allocation reduction translates to real performance benefits:
146
152
147
153
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
154
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.
155
+
Try identifying other opportunities for compound assignment operators in the codebase. Look for patterns where you use 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
156
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.
157
+
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 achieve small improvements.
0 commit comments