Quick Answer
Implement property accessors in C#.
Understanding the Issue
C# properties provide controlled access to class fields with get/set accessors, enabling validation and encapsulation.
The Problem
This code demonstrates the issue:
Csharp
Error
// Need to expose fields with validation
The Solution
Here's the corrected code:
Csharp
Fixed
// Basic property
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
// Auto-property (C# 3+)
public int Age { get; set; }
// Read-only property
public DateTime Created { get; } = DateTime.Now;
// Property with validation
private decimal _price;
public decimal Price {
get => _price;
set => _price = value >= 0 ? value : throw new ArgumentOutOfRangeException();
}
// Expression-bodied property (C# 6+)
public string FullName => $"{FirstName} {LastName}";
// Init-only property (C# 9+)
public string Address { get; init; }
Key Takeaways
Use properties instead of public fields for better encapsulation.