#Net5 – C#9 “Init-only properties” are super cool πŸ†’πŸ†’πŸ†’

Buy Me A Coffee

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. 
Csharp9 init only properties

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:

Advertisement

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: