-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Open
Labels
Description
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
Reactions are currently unavailable