Glossary / Classes
Classes
A C# class defines a reference type with state and behavior. Variables of a class type hold references to instances; assignment aliases the same object. Classes support encapsulation, single class inheritance, interface implementation, virtual dispatch, and identity-oriented models.
Members and object lifecycle
Classes can define fields, properties, methods, events, constructors, operators, nested types, and finalizers. new constructs an instance and invokes an instance constructor; object initializers can set accessible members afterward. A class can be abstract, sealed, static, or partial. Access modifiers define the public surface and assembly boundaries.
public sealed class Account
{
public decimal Balance { get; private set; }
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
Balance += amount;
}
}
Properties should protect invariants rather than expose mutable state indiscriminately. Reference identity and equality are distinct: default class equality is reference-based unless overridden, while records synthesize value equality. Garbage collection reclaims managed objects when unreachable, but external resources require deterministic disposal.
Design guidance
Use classes for identity, shared mutable state, complex behavior, or polymorphism. Favor composition over deep inheritance when behavior varies independently. Keep constructors valid and avoid exposing partially initialized objects. Use interfaces for capabilities and sealed classes when extension is not part of the contract.
Interview questions
- What does a class variable contain? A reference to an object.
- What is default equality? Reference identity unless overridden.
- Can C# inherit from multiple classes? No; a class has one base class but can implement multiple interfaces.
- Does GC dispose resources? Not deterministically; implement and call disposal patterns.
- When choose class over struct? Identity, shared mutation, inheritance, or larger state.