Unexpected redundant reference during C# lowering #71948
-
While experimenting with SharpLab to understand C# compiler optimizations, I observed an intriguing behavior during the lowering process of collection initializers. Specifically, initializing a The input: var foo = new HashSet<string>
{
"Foo",
"Foo",
}; gets converted to: HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("Foo");
hashSet.Add("Foo");
HashSet<string> hashSet2 = hashSet; Complete SharpLab demo: here The puzzling part:
I've attempted to find related discussions or documentation on compiler design decisions that might explain this behavior but to no avail. I'm curious if this pattern serves a specific purpose? Any insights or explanations would be greatly appreciated! Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is by design. The language says that this assigns to a temp and then finally assigns the temp to the final location.
THis is the actual compiler output.
Sure. Imagine you had the following:
We do not want 'set' to be in an intermediate state just because GetValue() failed. We want it to be totally initialized, or not at all. Similarly, we don't want any code that is executing to be able to look at 'set' and see it changing as that initializer runs. So we create a temp, initialize it, and do a final assignment when it completes successfully. |
Beta Was this translation helpful? Give feedback.
This is by design. The language says that this assigns to a temp and then finally assigns the temp to the final location.
THis is the actual compiler output.
Sure. Imagine you had the following:
We do not want 'set' to be in an intermediate state just because GetValue() failed. We want it to be totally initialized, or not at all.
S…