C# 14 introduces the field keyword, which allows you to write a property accessor body without declaring an explicit backing field. In this article, I present how to use this new feature.
In previous C# versions
In C#, we have two main options to use properties: Auto-implemented properties, which are concise but do not allow you to add logic in the property accessor, and the** Manual properties**, which require a private backing field.
For an Auto-implemented property, we can declare it like this:
public class Product
{
// Auto-implemented property.
public string Code { get; set; }
}This is quite simple, but it doesn’t allow you to add logic for the getter or setter. To do that in versions before C# 14, you had to manually create a private backing field:
public class Product
{
// Manual backing field.
private string _code;
public string Code
{
get => _code;
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("Invalid product code.", nameof(value));
_code = value.Trim().ToUpperInvariant();
}
}
}As you can see in the example above, we have the public property Code and a** private*** backing field* _code. This creates “noise” in your class, especially when you have many properties that require similar logic.
The field keyword in C# 14
With C# 14, when you need to add custom logic to the property, you no longer need to declare the private field. The compiler will automatically generate it for you, and you can access it directly using the field keyword inside the property accessors:
public class Product
{
public string Code
{
get;
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("Invalid product code.", nameof(value));
field = value.Trim().ToUpperInvariant();
}
}
}Conclusion
The field keyword removes unnecessary boilerplate when working with properties that require logic in a getter or setter, allowing you to write more concise code without sacrificing the ability to add logic to your setters and getters, and keeping your code cleaner.
This is the link for the project in GitHub: https://github.com/henriquesd/DotNet10.CSharp14.Demo
If you like this demo, I kindly ask you to give a ⭐️ in the repository.
Thanks for reading!
References