C# 6 Features: Expression Bodied Auto-Properties

by Joseph on Feb 3rd in .Net, C#

Today I’d like to look at something interesting that moves us a little further with Auto-Properties. Expression Bodied Auto-Properties. This concept is pretty neat because it lets us take the idea of Auto-Initializing a property, and making it unsettable, and then gives us the ability to add on a lamba expression into the mix!

The setup

Once again, we’re going to look at our poor person class. This time, we’re going to give him a Birthday.

[gist id=”f252f415da124a057e01″  file=”GiveThePersonABirthday.cs”]

I’ve also added a little bit of code to our PersonService in order to store the Birthday into the database.

[gist id=”f252f415da124a057e01″  file=”StoreTheBirthday.cs”]

Notice that we’re not storing an age in the database. This is going to be important later. After all – age can be calculated later, right?

We also need to make sure that the Birthday comes back from the database correctly.

[gist id=”f252f415da124a057e01″  file=”RetrieveTheBirthday.cs”]

Last, we need to create a person with a Birthday.

[gist id=”f252f415da124a057e01″  file=”CreateAPersonWithABirthday.cs”]

This was a lot of setup – but now we have a person, with a birthday, in our database.

Expression Bodied Auto Property

What I’d like to know is – how old is the person we’ve got in our database?

Traditionally, we would have treated this in one of a few different ways.

This is a View-Model concern – let the consumer worry about calculating it.

This is a reasonable response in some cases. Especially cases where you are providing a First Name, Middle Name, and Last Name, and one consumer wants a First Name and Last Name, and one consumer wants a First Name, Middle Initial, and Last Name. Let them sort it out.

In this case, though, let’s pretend our application is going to be used to screen whether people are old enough to… Drink, see an “R-Rated” movie, whatever. The idea here is that we are providing a means for the consumer application to get easy access to the age of the person stored.

Traditionally, we would add a Property onto the Person Class that looked something like this:

[gist id=”f252f415da124a057e01″  file=”TraditionalCalculatedProperty.cs”]

This is a typical Calculated Property. It has no setter, only a getter which returns the persons age.

Expression Bodied Auto Properties are very similar.

[gist id=”f252f415da124a057e01″  file=”ExpressionBodiedAutoProp.cs”]

This is one of the features that will be mostly about personal choice, and what works best for your team. Do you prefer the more verbose style of the traditional getter? Or do you prefer the Lambda Expression in Expression Bodied Properties?

Personally, I have a feeling I’ll need Resharper to remind me about Expression Bodies the first few times, but then it’ll become second nature.

Leave a Reply

Powered By Wordpress Designed By Ridgey