Today I Learned - Primary Constructors
I've recently found myself picking up C# again for a project and even though much of my knowledge applies, I recently found the following and it took me a minute to figure out what's up.
Let's say that we're working on the Mars Rover kata and we've decided to model the Rover type as a class with three fields: x, y, and direction.
My normal approach to this problem would have been the following:
However, in the code I was working with, I saw the Rover
definition as this
At first, I thought this was similar to the record syntax for holding onto data
And it turns out, that it is! This feature is known as a primary constructor and when used with classes, it gives you some flexibility on how you want to access those inputs.
For example, in our second implementation of Rover, we're directly using x
, y
, and direction
in the Print
method.
However, let's say that we didn't want to use those properties directly (or if we need to set some state based on those inputs), then we could do the following.
After playing around this for a bit, I can see how this feature would be beneficial for classes that only store their constructor arguments for later usage.
Even though Records accomplish that better, you can't attach functionality to Records, but you can with classes, so it does provide better organization from that front.
That being said, I'm not 100% sure why we needed to add the primary constructor feature to the language as this now opens up multiple ways of setting up constructors. I'm all for giving developers choices, but this seems ripe for bike shedding where teams have to decide which approach to stick with.