
Hi !
So this one does not fit in the line “readability improvement”, however is a nice step in order to write cleaner code. Yes, I know that doesn’t make sense, let me try to explain.
Let’s start with a simple class with 2 properties. Interesting enough the property Age has a new accessor [init] to describe the property as a read-only property:
class Pet
{
public string Name { get; set; }
public int Age { get; init; }
}
When we create a new Pet object, we can set the initial value of Age on the construction of the object (object initialization), and that’s it. Otherwise we will get this amazing error.
Error CS8852 Init-only property or indexer 'Program.Pet.Age' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

Until C#9, the properties in a class need to be mutable in order to support Object Initialization. And that means some extra code in the property-set definition in order to support read-only properties. Now in C# 9, this is solved with the [init] accessor πππ
I like this new one π ! Not a great readability improvement, but it saves us a lot of extra code.
Happy coding!
Greetings
El Bruno
More posts in my blog ElBruno.com.
More info in https://beacons.ai/elbruno
References
ΒΏCon ganas de ponerte al dΓa?
En Lemoncode te ofrecemos formaciΓ³n online impartida por profesionales que se baten el cobre en consultorΓa:
- Si tienes ganas de ponerte al dΓa con Front End (ES6, Typescript, React, Angular, Vuejs…) te recomendamos nuestros MΓ‘ster Front End: https://lemoncode.net/master-frontend#inicio-banner
- Si te quieres poner al dΓa en Backend (stacks .net y nodejs), te aconsejamos nuestro Bootcamp Backend: https://lemoncode.net/bootcamp-backend#bootcamp-backend/banner
- Y si tienes ganas de meterte con Docker, Kubernetes, CI/CD…, tenemos nuestro Bootcamp Devops: https://lemoncode.net/bootcamp-devops#bootcamp-devops/inicio