Skip to content

Commit e806d60

Browse files
committed
Update TransformCollectionAndObjectInitializers to check for init-only properties
1 parent 2f311c2 commit e806d60

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

ICSharpCode.Decompiler/IL/Transforms/TransformCollectionAndObjectInitializers.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ void IStatementTransform.Run(Block block, int pos, StatementTransformContext con
5858
{
5959
case NewObj newObjInst:
6060
if (newObjInst.ILStackWasEmpty && v.Kind == VariableKind.Local
61+
&& !TypeContainsInitOnlyProperties(newObjInst.Method.DeclaringType.GetDefinition())
6162
&& !currentMethod.IsConstructor
6263
&& !currentMethod.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
6364
{
@@ -187,6 +188,18 @@ void IStatementTransform.Run(Block block, int pos, StatementTransformContext con
187188
ILInlining.InlineIfPossible(block, pos, context);
188189
}
189190

191+
private static bool TypeContainsInitOnlyProperties(ITypeDefinition? typeDefinition)
192+
{
193+
foreach (var property in typeDefinition?.Properties ?? [])
194+
{
195+
if (property.Setter?.IsInitOnly ?? false)
196+
{
197+
return true;
198+
}
199+
}
200+
return false;
201+
}
202+
190203
internal static bool IsRecordCloneMethodCall(CallInstruction ci)
191204
{
192205
if (ci.Method.DeclaringTypeDefinition?.IsRecord != true)

ICSharpCode.Decompiler/NRExtensions.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,18 @@ public static bool ContainsAnonymousType(this IType type)
7373
return visitor.ContainsAnonType;
7474
}
7575

76+
public static bool ContainsInitOnlyProperties(this IType type)
77+
{
78+
foreach (var property in type.GetDefinition()?.Properties ?? [])
79+
{
80+
if (property.Setter?.IsInitOnly ?? false)
81+
{
82+
return true;
83+
}
84+
}
85+
return false;
86+
}
87+
7688
class ContainsAnonTypeVisitor : TypeVisitor
7789
{
7890
public bool ContainsAnonType;

0 commit comments

Comments
 (0)