📦 Properties = Encapsulation
Public fields break encapsulation. Properties control access. Get, set, validate — better code.
❌ Public Field
public class User
{
public string Name;
public int Age;
}
✅ Property
public class User
{
private string _name;
public string Name { get; set; }
public int Age { get; set; }
}
📝 Property Examples
// Auto-property
public string Name { get; set; }
// Read-only property
public string Email { get; private set; }
// Write-only property
public string Password { set; private get; }
// Property with validation
private int _age;
public int Age
{
get => _age;
set
{
if (value < 0 || value > 120)
throw new ArgumentException("Invalid age");
_age = value;
}
}
// Computed property
public string FullName => $"{FirstName} {LastName}";
// Expression-bodied property
public string DisplayName => Name ?? "Unknown";
// Init-only property
public string Id { get; init; }
// Property with backing field
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
// Static property
public static string AppName { get; set; }
// Abstract property
public abstract string Description { get; }
// Virtual property
public virtual string Info => $"Name: {Name}";
// Property with private set
public DateTime CreatedAt { get; private set; }
💡 Property Tips
- Use auto-properties for simple cases
- Add validation in setter
- Use private set for read-only
- Use init-only for immutable objects
- Use computed properties for derived values
“Properties control access. Get, set, validate. Essential for encapsulation.”
