
February 7, 2025 07:59 by
Peter
C#13's Preview functionality is now semi-auto-implemented Properties. When specifying properties in class files, this feature greatly improves readability and cuts down on boilerplate code. Let's examine one straightforward situation to gain a better understanding.

Situation
Typically, an auto-implemented property is declared in C#.
public int EmplSalary { get; set; }
The compiler automatically generates a backing field like (Ex: _empSalary) and internal getter/setter methods (void set_EmplSalary(int empSalary) and int get_EmplSalary()).
However, In our real-time project cases, we need to set some custom logic such as validation, default values, computations, or lazy loading in the property’s getter or setter, we typically need to manually define the backing field.
C# 13 preview
This process is simplified by the introduction of the field keyword, which allows direct access to the backing field without the need for manual definition, as this feature is currently in the Preview stage. We have to apply the following keyword to use this in our project settings. Edit the project file by adding <LangVersion>preview</LangVersion>. So, It supports field property in project usage.

The following code gives a more illustrative idea about usage.
Before .NET 9
private int _empSalary;
/// <summary>
/// Before .NET 9
/// </summary>
public int EmpSalary
{
get => _empSalary;
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value),
"Salary must be greater than 0");
_empSalary = value;
}
}
.NET 9 (Preview)
/// <summary>
/// In .NET 9
/// </summary>
public int EmployeeSalary
{
get => field;
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value),
"Salary must be greater than 0");
field = value;
}
}
Benefits
- Less Boilerplate Code: Removes the necessity for private backing fields, leading to more streamlined and concise code.
- Enhanced Readability: Eliminates concerns about naming backing fields, as the standardized field keyword improves code clarity.
- Property-Scoped Field: The private property field is accessible only within the property itself, ensuring better encapsulation and preventing unintended access elsewhere in the parent class. This key feature of C# 13 Semi-Auto Properties effectively mitigates a common source of errors.
Please also read Understanding UUID v7 in .NET 9 for other .NET9 related features.
Summary
This feature helps in our project's day-to-day scenarios with the benefits of Less Boilerplate Code, Enhanced Readability, and Property-Scoped Fields. As this feature is still in Preview mode, please use it with caution in our real-time projects.