Skip to main content

Semi-Auto Properties

  • Semi-Auto Properties

  • When you declare an auto-implemented property in C# public int Number { get; set; }, the compiler generates a backing field (e.g., _number) and internal getter/setter methods void set_Number(int number) and int get_Number(). But if you need custom logic like validation, default values, computations, or lazy loading in a property’s getter or setter, you usually have to manually define the backing field in your class. C# 13 simplifies this by introducing the field keyword, allowing you to access the backing field directly without defining it manually.

// Before
public class MagicNumber
{
private int _number;

public int Number
{
get => _number * 10;
set {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Value must be greater than 0");
_number = value;
}
}
}

// .NET 9
public class MagicNumber
{
public int Number
{
get => field;
set {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Value must be greater than 0");
field = value;
}
}
}