C# 6 Features: AutoProperty Initializers
by Joseph on Feb 1st in .Net, C#
Last week, I started discussing the new C# 6 features introduced in Visual Studio 2015. The first entry discussed my personal favorite – String Interpolation. Today, I’d like to focus on Auto-Property Initializers. To get started, let’s take a look at our Person class that we’ve used a few times already. It’s pretty simple, and will be a great candidate for this process.
[gist id=”971b7e715b153cc9297b” file=”Auto-Properties_Before.cs”]
The interesting piece is that the output generated looks a bit like this:
What are our options?
Runtime Initialization
We could initialize the Property when we initialize the Class at Runtime. That is a valid option in some scenarios. In that case, our code would be modified to look something like this:
[gist id=”971b7e715b153cc9297b” file=”RuntimeInitialization.cs”]
But in the case of a Person, maybe we’re trying to write the Person to a database, so we want the Person Repository, or the Data Access layer, or some other area of the application to be responsible for assigning an ID. Not the UI or Business Layer.
Additionally, what happens if the person is sent through a service, and for some reason, the PersonId hasn’t been initialized. General rule of thumb – don’t trust anyone to initialize the properties on your objects!
Constructor Initialization
Which brings us to an old favorite – Initializing our properties to default values in the constructor. This is a tried and true method, though a little annoying. It’s not so bad with one Property, but when you have several, it get’s a little irritating.
[gist id=”971b7e715b153cc9297b” file=”ConstructorInit.cs”]
Auto-Property Initializers
Here is the first use case of Auto-Property Initializers. Essentially, you’re just cutting down on things you have to juggle when you’re reading, and writing code, not to mention learning a new code-base.
[gist id=”971b7e715b153cc9297b” file=”Auto-Property-Initializer.cs”]
We’ll look at some other use cases next time, such as Immutable Auto-Properties, Expression-Bodied Auto-Properties, and static Auto-Properties.
Other Posts in Series: