βœ… 𝗖# 𝟭𝟯: A Deep Dive into Semi-Auto Properties with the 𝗳𝗢𝗲𝗹𝗱 Keyword

Apurv upadhyay
4 min readOct 27, 2024

--

https://www.linkedin.com/in/apurvupadhyay/
C# Tips

C# 13 introduces a powerful new feature: semi-auto properties using the 𝗳𝗢𝗲𝗹𝗱 keyword. This addition simplifies the creation of properties by providing access to a property’s backing field directly in the getter and setter, without requiring you to define it manually. This improvement reduces boilerplate code, enhances readability, and encapsulates the backing field within the property itself. Let’s dive into the details and benefits of this feature.

πŸ”‘ The Evolution of Properties in C#

In C#, properties have traditionally required manual backing fields when any custom logic β€” like validation or lazy loading β€” was needed in a getter or setter. For example, if you wanted to add validation, you’d have to define a private field and then use it within the property’s getter or setter. This approach could add unnecessary complexity and reduce readability, especially in classes with multiple properties.

Example Before C# 13:

public class Example 
{
private int _number; // Custom backing field

public int Number
{
get => _number; // Custom getter
set
{
if (value < 0) throw new ArgumentException("Value cannot be negative");
_number = value; // Custom setter with validation
}
}
}

With C# 13, the 𝗳𝗢𝗲𝗹𝗱 keyword allows us to access the automatically generated backing field directly within the property, without manually defining it. This significantly reduces boilerplate and makes the code cleaner.

Example After C# 13:

public class Example 
{
public int Number
{
get => field; // Direct access to backing field
set
{
if (value < 0) throw new ArgumentException("Value cannot be negative");
field = value; // Assign directly to backing field
}
}
}

🎯 Key Benefits of Semi-Auto Properties with 𝗳𝗢𝗲𝗹𝗱

1. Reduced Boilerplate Code:

β€’ With semi-auto properties, there’s no need to define a private field manually, making code more concise.

β€’ This reduces repetitive code, especially in classes with several properties, where each property might require a private field for handling validation or custom logic.

2. Enhanced Readability:

β€’ The 𝗳𝗢𝗲𝗹𝗱 keyword introduces a standard that avoids custom field names, making code more readable and consistent.

β€’ It clearly indicates that the backing field belongs to the property, helping developers understand the property structure quickly.

3. Property-Scoped Field:

β€’ The 𝗳𝗢𝗲𝗹𝗱 keyword confines the backing field to the property itself, providing stronger encapsulation.

β€’ This encapsulation helps prevent accidental misuse elsewhere in the class and reduces potential bugs from accessing the backing field directly.

4. Improved Encapsulation and Safety:

β€’ By confining the backing field to the property, semi-auto properties enhance encapsulation, allowing the field to remain private to the property.

β€’ This reduces the chance of accidental modifications, making your code safer and more reliable.

🚨 Potential Breaking Change Alert

While the 𝗳𝗢𝗲𝗹𝗱 keyword is a great addition, it introduces a potential breaking change. If your class already has a property or field named 𝗳𝗢𝗲𝗹𝗱 of the same type, it can override the new keyword, leading to unexpected behavior. This was a major reason why this feature, first proposed in 2016, took time to implement in C#.

How to Use the 𝗳𝗢𝗲𝗹𝗱 Keyword for Semi-Auto Properties

The 𝗳𝗢𝗲𝗹𝗱 keyword is straightforward to implement and can be added in any property where you want to access the backing field without manually defining it.

Code Example with Validation Logic Using 𝗳𝗢𝗲𝗹𝗱

Suppose you have a property where you want to set a minimum value constraint:

public class ScoreTracker
{
public int MinimumScore
{
get => field;
set
{
if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), "Score cannot be negative.");
field = value; // Direct access to the backing field
}
}
}

Here:

β€’ The property MinimumScore leverages 𝗳𝗢𝗲𝗹𝗱 to enforce a minimum score of 0.

β€’ There’s no need to create a separate backing field, simplifying the code and enhancing readability.

Example with Lazy Loading Logic

You might also use the 𝗳𝗢𝗲𝗹𝗱 keyword in properties where lazy loading is required:

public class LazyLoader
{
public string Data
{
get
{
if (field == null)
{
field = LoadData(); // Lazy-load the data only when accessed
}
return field;
}
}

private string LoadData() => "Loaded Data";
}

Here:

β€’ The Data property only loads data on first access, and the backing field (𝗳𝗢𝗲𝗹𝗱) is used to store the result.

β€’ This approach avoids the need for a separate backing field variable and keeps the lazy-loading logic confined to the property.

🎯 Key Takeaways

β€’ Streamlined Code: With semi-auto properties, you don’t need to define custom backing fields, making properties cleaner and reducing redundancy.

β€’ Consistency and Readability: By using 𝗳𝗢𝗲𝗹𝗱 as a standard keyword, you avoid naming inconsistencies, making code more readable and easier to understand.

β€’ Improved Encapsulation: The backing field is now scoped to the property itself, enhancing safety and reducing the chance of unintended access.

β€’ Potential Conflicts: Be mindful of possible conflicts if you already have a property named 𝗳𝗢𝗲𝗹𝗱, as it may override the new keyword’s functionality.

Why This Matters for Developers

With semi-auto properties, C# 13 makes it easier to add custom logic to properties without bloating your code with unnecessary backing fields. By simplifying property management, C# aligns with its goal of enhancing code readability, encapsulation, and developer productivity.

❀️ Share Your Thoughts!

Feel free to repost ♻️ if you found this helpful. For more great content like this follow πŸ›  Apurv Upadhyay. Until next time, happy coding! πŸš€

#CSharp13 #DotNet #CodingTips #CleanCode #Properties #DotNet9 #SoftwareDevelopment

--

--

Apurv upadhyay
Apurv upadhyay

Written by Apurv upadhyay

Principal Software Engineer at PeerIslands β€’ Microsoft Azure Certified Architect Expert & DevOps Specialist β€’ 7x Azure Certified β€’ ex-Microsoft, Bosch

No responses yet