I tried writing some C# code to create an init-only property. I was surprised to find that the property could be changed at run-time. Have I misunderstood the idea of immutability? I am using Visual Studio Community 16.9.3.
Sample code.
namespace TonyStachnicki.Windows {
using System.Management.Automation;
[Cmdlet(VerbsCommon.New, "Person")]
public class NewPerson : Cmdlet {
protected override void ProcessRecord() {
var _Person = new Person {
Name = "Jane Dough"
};
WriteObject(_Person);
}
}
public class Person {
public string Name { get; init; }
}
}
Run time example.
PS D:\Users\Tony> ($Person = New-Person)
Name
----
Jane Dough
PS D:\Users\Tony> $Person.Name = "John Smith"
PS D:\Users\Tony> $Person
Name
----
John Smith
PS D:\Users\Tony> $Person.Name = "Jane Jones"
PS D:\Users\Tony> $Person
Name
----
Jane Jones
PS D:\Users\Tony>
The program behaves the same with this Person class.
public class Person {
public string Name {
get { return m_Name; }
init { m_Name = value; }
}
private readonly string m_Name;
}
In this case the readonly modifier is also ignored.
I think most people would be surprised at the effect of the init-only feature.