Initializing auto-implemented properties in C#

In the version 6.0 of C #, the auto-implemented properties, those that we all known – that has a getter and a setter- can be initialized in their definition. We will see what are the advantages of using them and how they can help us.

How can we use it?

Let’s see a comparison with a simple example, how to initialize an auto-implemented property:

As we have seen in line 14, you can combine the declaration with the initialization in the same statement, using the assignment operator just after the declaration to indicate the value of the property.

Advantage

If we analyze the previous example, at first glance the first advantage is that less code is written and that is enough for me 😄, imagine all the time savings when we initialize properties in this way, prior to this we would have to do it in the constructor, and if we had more than one, we would have to repeat the process, so we also avoided code duplication.

Bonus

Read-Only Properties

We can also create a read-only property by initiating it with just a get, as we see in the example below.

Summary

The initialization of auto-implemented properties is a new feature introduced several versions ago of C #, in version 6.0 to be specific, and although it seems very simple, it allows us to write less code, it helps us to be cleaner and in conjunction with other language features such as String Interpolation our code becomes more readable. So when it comes to refactoring a class, keep in mind what you just learned, and surely the number of lines will be reduced and everything will be clear.