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.
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
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
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;
}
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!