C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Properties

C# Properties

Properties are the C# way to expose class data with controlled get/set access — cleaner than public fields and more flexible than explicit getter/setter methods.

1 - Auto-Implemented Properties

public class Person
{
    public string Name { get; set; }
    public int    Age  { get; set; } = 18; // default value
}

var p = new Person { Name = "Alice", Age = 30 };
Console.WriteLine(p.Name); // Alice

2 - Read-Only Properties

public class Circle
{
    public double Radius { get; }

    public Circle(double radius) => Radius = radius;

    // Computed property
    public double Area      => Math.PI * Radius * Radius;
    public double Perimeter => 2 * Math.PI * Radius;
}

var c = new Circle(5);
Console.WriteLine($"Area: {c.Area:F2}"); // Area: 78.54

3 - Properties with Validation

public class BankAccount
{
    private decimal _balance;

    public decimal Balance
    {
        get => _balance;
        private set
        {
            if (value < 0) throw new ArgumentException("Balance cannot be negative");
            _balance = value;
        }
    }

    public void Deposit(decimal amount) => Balance += amount;
}

4 - init-Only Properties (C# 9+)

public class Config
{
    public string Host { get; init; } = "localhost";
    public int    Port { get; init; } = 5432;
}

// Set during initialisation only
var cfg = new Config { Host = "db.example.com", Port = 5433 };
// cfg.Host = "other"; // compile error — init only!

Note: Prefer auto-implemented properties over public fields. Properties let you add logic later (logging, validation, change notification) without breaking callers, whereas public fields cannot be upgraded without an API break.

-Tip-