🔒 Properties Encapsulate, Fields Store
Fields store data. Properties control access. Validation, computed values, change tracking. Use properties, not public fields.
📘 Field
public class User
{
public string Name; // Field (direct access)
public int Age; // No validation
}
📗 Property
public class User
{
private string _name;
public string Name
{
get => _name;
set => _name = value?.Trim() ?? throw new ArgumentException();
}
}
🎯 Property Types
// Auto-property (C# 3.0)
public string Name { get; set; }
// Read-only (init only)
public string Name { get; init; }
// Private set
public string Name { get; private set; }
// Computed
public string FullName => $"{FirstName} {LastName}";
// With validation
private int _age;
public int Age
{
get => _age;
set
{
if (value < 0 || value > 150)
throw new ArgumentException("Invalid age");
_age = value;
}
}
// Expression-bodied
public string Name
{
get => _name;
set => _name = value;
}
💡 When to Use
- Public fields: Never (except constants)
- Properties: Always for public data
- Private fields: Store data for properties
- Auto-properties: For simple data
- Read-only properties: For computed values
“Properties encapsulate fields. Use properties, not public fields. Essential for OOP.”
