Daily Knowledge Drop
An expression
can be used as the body of a constructor, providing a more concise (but arguably, more complex) style.
Traditional constructor
Traditionally, the constructor for an entity would have a parameter for each property of the entity and set the property value to the parameter value (or to a default):
public class Song
{
public string Artist { get; set; }
public string Name { get; set; }
public int LengthInSeconds { get; set; }
// set all property values based on parameters
public Song(string artist, string name, int lengthInSeconds)
{
Artist = artist;
Name = name;
LengthInSeconds = lengthInSeconds;
}
// set property values based on parameters and
// default values
public Song(string artist, string name)
{
Artist = artist;
Name = name;
LengthInSeconds = 0;
}
}
While there is absolutely nothing wrong with this approach, it is a fair number of lines of code just to set a few properties. A more concise approach, would be to use an expression
for the body of the constructor.
--
Expression-bodied constructor
The constructors can be rewritten as follows, using expressions for the body of the constructor:
public class Song
{
public string Artist { get; set; }
public string Name { get; set; }
public int LengthInSeconds { get; set; }
// set all property values based on parameters
public Song(string artist, string name, int lengthInSeconds) =>
(Artist, Name, LengthInSeconds) = (artist, name, lengthInSeconds);
// set property values based on parameters and
// default values
public Song(string artist, string name) =>
(Artist, Name, LengthInSeconds) = (artist, name, 0);
}
Here, a powerful feature of Tuples
is leveraged. A Tuple created from the values passed into the constructor (or default values), is assigned to a Tuple created using the properties of the class. This will essentially assign the parameter values to the property values
.
Definitely a more concise approach, although if unfamiliar with the syntax and how Tuples work, can definitely be a more confusing approach.
Notes
If concise, lean and clean code is the goal, then expression-body constructors
is the way to go. As mentioned, the syntax can be more confusing when compared with the traditional approach - especially to those unfamiliar with Tuples and their properties.
References
Daily Drop 244: 27-01-2023
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.