Skip to content

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

@nikitalita

Description

@nikitalita

If an object with init-only properties is initialized in a function outside of a constructor, and it happens to be allocated locally and isn't in a compiler generated method/class, then ILSpy won't use an object initializer for it and will instead attempt to set the properties after using the default constructor, which results in the compile failing.

Please note: the following is dependent on whether or not the C# compiler decides to allocate the object assigned to field1 on the stack or the heap, and I can't figure out a consistent method of forcing it to allocate on the heap.

Input code

    public class Bar{
        public int? Prop1 { get; init; }
    }

    public class BarInitializer{
        public volatile Bar? field1 = null;
        public BarInitializer()
        {
            initialize();
        }

        private void initialize()
        {
            field1 = new Bar
            {
                Prop1 = 1
            };
        }
    }

Erroneous output

    public class Bar{
        public int? Prop1 { get; init; }
    }

    public class BarInitializer{
        public volatile Bar? field1 = null;
        public BarInitializer()
        {
            initialize();
        }

        private void initialize()
        {
            field1 = new Bar();
            field1.Prop1 = 1; // Prop1 is init-only, so this is an compile error
        }
    }

If the output fails to re-compile, provide the compiler error message.
If the output has the wrong behavior, explain how it differs from the expected behavior.

Details

  • Product in use: ILSpyCmd
  • Version in use: current master

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugDecompilerThe decompiler engine itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions