Menu

Friday, 17 January 2025

Semi Auto Properties in .NET9

 

About


The series of features exploring in .NET 9 posts, This post, we are focusing on "Semi Auto Properties" feature in .NET9. Please refer the following links for other .NET 9 features discussed in my earlier posts.

Introduction


Semi Auto Properties is available in Preview feature of C#13. This feature really helps Enhanced readability and reduced boilerplate code while declaring properties in class files.

Lets understand further by exploring more following information.

Usually, In C#, We declare an auto-implemented property like 
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. 
With 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.

Edit the project file by adding <LangVersion>preview</LangVersion>. So, It supports field
property in project usage.


The following code gives more illustrative idea about usage.

Before .NET 9


private int _empSalary;

public int EmpSalary
{
    get => _empSalary;
    set
    {
        if (value <= 0)
            throw new ArgumentOutOfRangeException(nameof(value),
                "Salary must be greater than 0");
        _empSalary = value;
    }
}

In .NET 9


public int EmployeeSalary
{
    get => field;
    set
    {
        if (value <= 0)
            throw new ArgumentOutOfRangeException(nameof(value),
                "Salary must be greater than 0");
        field = value;
    }
}


Code Screenshot




Thanks for your reading and please share your feedback on comments.

No comments:

Post a Comment