Now that we’ve seen how to create Auto-Property Initializers, let’s take a look at another new feature of Auto-Properties: Immutable Auto-Properties.
For our use-case, I’d like to recall the PersonService class we created during the Simple Injection Example. In this example, we created a new person, then passed it to a service to save the new person to a database. The service was responsible for returning a new PersonId. From the perspective of the Console Application, it didn’t matter if the PersonId was generated in the Database, or if it was generated in the service.
As we see here, the ID is generated and returned, and does not need to be accessed on the class from the Console Application. However – as the class stands currently, the PersonId could be changed at any time. This could result in problems saving the Person back to the database, or it could simply cause confusion accessing the class in later uses of the API.
The first adjustment we can make is to simply change the Person Class to have a Getter Only Auto Property – which can then be Auto-Initialized to Guid.Empty.
This prevents us from inadvertently changing the PersonId once it is set.
There is one more thing we’ll want to change though…
In our PersonService Class, we have a GetPerson method that retrieves the person from the database and sets up the properties. Because we have made the AutoProperty Read-Only, we need to have some way to get it into the class. The answer is Constructor Injection. And everything comes full circle.
will become this:
And now the Person class looks a little like this:
Because we’re passing the PersonId in through the constructor, it is able to initialize correctly, and maintain its read-only status. In addition, if the parameterless constructor is used, the PersonId will still have a default of Guid.Empty.
Honestly, this is only the tip of the iceberg of immutability. Eric Lippert wrote in 2007 that Immutability is the “Way of the Future” in C#. There are a number of great articles detailing the uses and benefits of immutability in general, but I recommend starting there.
Other Posts in Series