C# 6 Features: Immutable Auto-Properties

by Joseph on Feb 2nd in .Net, C#

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.

[gist id=”b9be80285d390d7a7764″ file=”AccessPersonWithPublicId.cs”]

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.

[gist id=”b9be80285d390d7a7764″ file=”ReadOnlyPersonId.cs”]

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.

So this:

[gist id=”b9be80285d390d7a7764″ file=”GetPersonWithPublicId.cs”]

will become this:

[gist id=”b9be80285d390d7a7764″ file=”GetPersonWithReadOnlyId.cs”]

And now the Person class looks a little like this:

[gist id=”b9be80285d390d7a7764″ file=”PersonWithNewConstructor.cs”]

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.

Source Code

This Source Code is in Github

Other Posts in Series

Leave a Reply

Powered By Wordpress Designed By Ridgey