Defining a Class
Use the class keyword. Fields store data; methods define behaviour. By convention, class names use PascalCase and file names match the class name.
public class BankAccount
{
private decimal _balance;
public string Owner { get; }
public BankAccount(string owner, decimal initialBalance)
{
Owner = owner;
_balance = initialBalance;
}
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentException("Amount must be positive");
_balance += amount;
}
public bool Withdraw(decimal amount)
{
if (amount > _balance) return false;
_balance -= amount;
return true;
}
public override string ToString()
=> $"Account[{Owner}]: {_balance:C2}";
}Properties
Properties expose fields safely using get and set accessors. Auto-properties generate the backing field automatically. init accessors allow setting a value only during object initialisation.
public class Person
{
// Auto-property with init
public string Name { get; init; } = string.Empty;
public int Age { get; set; }
// Computed property
public bool IsAdult => Age >= 18;
}
var p = new Person { Name = "Alice", Age = 22 };
Console.WriteLine(p.IsAdult); // True
// p.Name = "Bob"; // โ compile error โ init-onlyC# 14 Primary Constructors
C# 14 lets you declare constructor parameters directly on the class declaration. The parameters are in scope throughout the entire class body.
// C# 14 primary constructor โ no boilerplate
public class Customer(string name, string email)
{
public string Name { get; } = name;
public string Email { get; } = email;
public void Send(string message)
=> Console.WriteLine($"Emailing {Email}: {message}");
}
var c = new Customer("Alice", "[email protected]");
c.Send("Your order has shipped!");Static Members
A static member belongs to the class itself, not to any instance. Access it through the class name, not an object reference.
public class Counter
{
public static int Total { get; private set; } = 0;
public int Id { get; }
public Counter()
{
Total++;
Id = Total;
}
}
var a = new Counter(); // Total = 1
var b = new Counter(); // Total = 2
Console.WriteLine(Counter.Total); // 2