-
The following code should swap values in a and b: int a = 3, b = 5;
a ^= b ^= a ^= b;
Console.WriteLine($"a = {a}, b = {b}"); but it gives wrong result: But the code with separated assignments works: int a = 3, b = 5;
a ^= b;
b ^= a;
a ^= b;
Console.WriteLine($"a = {a}, b = {b}"); producing: Environment: C:\Program Files\dotnet>dotnet --version
8.0.100
C:\Program Files\dotnet>dotnet --list-sdks
8.0.100 [C:\Program Files\dotnet\sdk]
C:\Program Files\dotnet>dotnet --list-runtimes
Microsoft.AspNetCore.App 8.0.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 8.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 8.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 3 replies
-
Well, that was a fun little rabbit hole. Of the langs I tested, C++ and PHP do what you want If you look at the IL it's easy to see why it behaves like that in C#, and I'd very strongly assume it's a deliberate choice. |
Beta Was this translation helpful? Give feedback.
-
This seems like a pretty esoteric case, and the language has probably done this since C# 1.0. I guess the question is what the language specification states that the language should do and whether it's worth amending. If the language spec implies that this should work as you described, then I would post to the Roslyn repository as a compiler bug. |
Beta Was this translation helpful? Give feedback.
-
So, the expression I don't see statements kinda "correct work of esoteric cases is not guaranteed" or "when in doubt, consult with C++/PHP/whatever language agreements" or "correct work of associative operators in chain is guaranteed only for chains of length not more than 2" (because I'll report my previous post to Roslyn repo, thanks all. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
The explanation why the result observed is as intended see in Roslyn thread. |
Beta Was this translation helpful? Give feedback.
The explanation why the result observed is as intended see in Roslyn thread.