A useful new feature in C# 9, init only setters for properties, allows us to have truly immutable objects or variables.
The new init option for variables can be used where we are used to using get; and set;. For example, this object representing a tech meetup.
Snippet 1 👩💻:
We can now only set the topic field on initalise of the object. See code snippet 2. You'll notice this is all in one Program.cs for demo purposes. See previous post on top level programs in C#9.
Snippet 2 👩💻:
When this runs, the output is as expected:
Now, when we try to override the values, we can see where the init property comes in.
Snippet 3 👩💻:
This example won't compile, as we cannot set the City of a Meetup after it's initialised. See build output:
To allow us to have an object identical to the glasgowMeetup, with a different city we can create a new copy of it then override the init only field. We do this using with, to create an edinburghMeetup object that is copy of glasgow but with City overridden.
Snippet 4 👩💻:
See output to this code below. You'll notice any update to the glasgowMeetup after we copy it using with is not reflected to the edinburghMeetup object.
I hope this was useful! As always, please say hello on twitter.