UPDATE (9/23/2021): This feature, unfortunately, did not make it into C# 10. This post was written before the feature set for C# 10 was finalized. I'm leaving it up, but know that the demo in this post won't work in C# 10. You can track the corresponding feature request on GitHub.
The next feature in our Bite-Size C# 10 series is one that could make our classes a whole lot less cluttered: semi-auto properties, using the field
keyword!
Current Implementation
In C# 9.0 and below, we have the concept of auto-implemented properties:
public class Employee
{
public string HireDate { get; set; }
}
This is great, so long as you don't want to do any processing to any of these values during instantiation. Say, for example, that we want only the Date
portion of a given DateTime
object to be saved into the HireDate
field. To do this, we have to use a backing property:
public class Employee
{
private DateTime _hireDate;
public DateTime HireDate {
get
{
return _hireDate;
}
set
{
_hireDate = value.Date;
}
}
}
That's quite a bit of code for one little change!
New Implementation
In C# 10, the new field
keyword can be used to replace the backing property from the previous code block. We can simplify our Employee
class like so:
public class Employee
{
public DateTime HireDate { get; set => field = value.Date; }
}
Note that if the property was declared with the init
setter introduced in C# 9.0 instead of set
, the field
keyword will still work correctly.
public class Customer
{
public DateTime DateOfVisit { get; init => field = value.Date; }
}
Other Considerations
At the time of writing, this feature has not been included in the 10.0 milestone from the C# team. This may mean that this feature won't actually make it into C# 10. Please keep this in mind.
Demo Project
This feature is included in my demo project for this series, however it won't compile at the moment, since semi-auto properties are not included in the C# 10 preview at publishing time.
Happy Coding!