Classes are how C# programs model their domain and organize behavior with data.
A class is a blueprint for objects bundling data and behavior. You create an instance with new: var acc = new Account("Ada"); or with target-typed Account acc = new("Ada");.
Members of a class:
- Fields hold state, conventionally
privateand named_balance. - Constructors initialize a new object and share the class name. Since C# 12, a class can have a primary constructor:
class Account(string owner)makesowneravailable throughout the class body. - Methods act on the object's state;
thisrefers to the current instance. - Properties expose data with get/set logic (next lesson).
staticmembers belong to the type itself rather than to any instance, likeMath.Max.
Access modifiers control visibility: public (everyone), private (the class itself, the default for members), protected (the class and subclasses), internal (the same assembly, the default for top-level types).
Objects are reference types allocated on the managed heap; variables hold references. Two variables can point at the same object, and == on classes compares references unless the class overrides it. The garbage collector frees objects once nothing references them, so there is no delete.
Keep invariants inside the class: validate in the constructor and in mutating methods, and throw an exception for invalid input instead of letting the object reach a bad state.
Example
var acc = new Account("Ada");
acc.Deposit(100);
acc.Withdraw(30);
Console.WriteLine(acc.Describe()); // Ada: 70
Console.WriteLine(Account.Count); // 1
class Account(string owner)
{
private decimal _balance;
public static int Count { get; private set; }
private readonly int _id = ++Count; // runs for each new instance
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
_balance += amount;
}
public void Withdraw(decimal amount) => _balance -= amount;
public string Describe() => $"{owner}: {_balance}";
}Remember
- new creates an instance; constructors set it up
- Fields private, behavior public: keep invariants in the class
- static members belong to the type, not to instances
- Class variables hold references; GC reclaims unreachable objects
Watch out for
- Making every field public, so any code can put the object into an invalid state.