Skip to content

Update TransformCollectionAndObjectInitializers to check for init-only properties#3678

Merged
siegfriedpammer merged 2 commits intoicsharpcode:masterfrom
nikitalita:fix-obj-initializers
Mar 18, 2026
Merged

Update TransformCollectionAndObjectInitializers to check for init-only properties#3678
siegfriedpammer merged 2 commits intoicsharpcode:masterfrom
nikitalita:fix-obj-initializers

Conversation

@nikitalita
Copy link
Copy Markdown
Contributor

Problem

Fixes #3677

Solution

The main culprit was here:

					if (newObjInst.ILStackWasEmpty && v.Kind == VariableKind.Local
						&& !currentMethod.IsConstructor
						&& !currentMethod.IsCompilerGeneratedOrIsInCompilerGeneratedClass())

Adding a simple check to see if the declaring type has init-only properties fixes the issue.

I would add a test that covers this, but I do not know how to force the C# compiler to allocate an object locally instead of on the stack consistently; if you have any tips, let me know.

@nikitalita nikitalita force-pushed the fix-obj-initializers branch from 4134411 to a6b4824 Compare March 15, 2026 23:33
@siegfriedpammer
Copy link
Copy Markdown
Member

I would add a test that covers this, but I do not know how to force the C# compiler to allocate an object locally instead of on the stack consistently; if you have any tips, let me know.

I couldn't find a definitive rule for when the Roslyn compiler uses local slots over stack slots. The main observation is that Roslyn prefers stack over locals especially in Release builds.

Some of the things just cannot be tested in C# pretty tests so you may have to resort to IL pretty tests.

Comment thread ICSharpCode.Decompiler/NRExtensions.cs Outdated
@nikitalita nikitalita force-pushed the fix-obj-initializers branch from a6b4824 to e806d60 Compare March 16, 2026 07:57
@nikitalita nikitalita force-pushed the fix-obj-initializers branch from e806d60 to dabfc75 Compare March 16, 2026 07:58
Comment thread ICSharpCode.Decompiler/IL/Transforms/TransformCollectionAndObjectInitializers.cs Outdated
…ectInitializers.cs

Co-authored-by: Siegfried Pammer <siegfried@pammer.io>
@siegfriedpammer siegfriedpammer merged commit 9ed9622 into icsharpcode:master Mar 18, 2026
5 checks passed
@nikitalita nikitalita deleted the fix-obj-initializers branch March 23, 2026 16:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ILSpy does not use object initializers for class/structs with init-only properties

2 participants