Types that keep their promises
Imagine a savings account represented by a plain decimal variable. Any line of code anywhere in the program can set it to a negative number, and nothing stops it. Now imagine a SavingsAccount type whose balance can be read by anyone but changed only through Deposit and TryWithdraw, which refuse nonsense. The second design has an invariant, a promise that is always true ("the balance is never negative"), and the type itself keeps the promise. Nobody has to remember it.
That is the point of defining your own types. C# gives you three kinds: classes, structs and records, each with different rules for copying and comparing. Learning which one to reach for, and how to expose data through properties without giving up control, is the heart of everyday C# design.
Classes and properties
A class is a blueprint for objects. It bundles data (fields and properties) with behaviour (methods), and controls who can see what with access modifiers: public (anyone), private (only this type, the default for members), protected (this type and types derived from it) and internal (anything in the same assembly, the default for top-level types).
Definition— Property
A member that looks like a field to its callers (account.Balance) but is implemented by a get accessor, and optionally a set or init accessor, which are methods. A property lets a type validate, compute or restrict access to a value while keeping simple syntax for callers.
Public data in C# is almost always exposed as properties, not fields. Properties can change their implementation later (add validation, compute a value) without changing any caller, and many libraries (serialisers, UI binding) work with properties only.
Here is the savings account:
var account = new SavingsAccount("Fatima Zahra", 100m);
account.Deposit(250m);
Console.WriteLine(account);
if (!account.TryWithdraw(500m))
Console.WriteLine("Withdrawal of 500 refused: insufficient funds.");
account.TryWithdraw(120m);
Console.WriteLine(account);
account.Owner = " Fatima Zahra Benali ";
Console.WriteLine($"Owner is now '{account.Owner}'");
Console.WriteLine($"Accounts opened: {SavingsAccount.Opened}");
try
{
account.Owner = " ";
}
catch (ArgumentException e)
{
Console.WriteLine($"Rejected: {e.Message}");
}
class SavingsAccount
{
// A static field belongs to the class, shared by every instance.
public static int Opened { get; private set; }
// C# 14: 'field' refers to the compiler-generated backing field.
public string Owner
{
get;
set
{
ArgumentException.ThrowIfNullOrWhiteSpace(value);
field = value.Trim();
}
}
// Anyone can read the balance; only this class can change it.
public decimal Balance { get; private set; }
public SavingsAccount(string owner, decimal openingDeposit)
{
Owner = owner;
Deposit(openingDeposit);
Opened++;
}
public void Deposit(decimal amount)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
Balance += amount;
}
public bool TryWithdraw(decimal amount)
{
if (amount <= 0 || amount > Balance) return false;
Balance -= amount;
return true;
}
public override string ToString() => $"{Owner}: {Balance:F2}";
}It prints:
Fatima Zahra: 350.00
Withdrawal of 500 refused: insufficient funds.
Fatima Zahra: 230.00
Owner is now 'Fatima Zahra Benali'
Accounts opened: 1
Rejected: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'value')What to notice:
new SavingsAccount(...)calls the constructor, the special method with the class's name and no return type. Its job is to leave the object in a valid state.Balance { get; private set; }is an auto-property: the compiler creates a hidden field to store the value. Anyone can read it; only code inside the class can assign it. The only ways to change the balance areDepositandTryWithdraw, and both check their input, so the invariant holds.- The
fieldkeyword (C# 14) lets a property's accessor refer to the compiler's hidden backing field. Before C# 14, adding validation to one accessor meant declaring a private field by hand and writing both accessors out. Hereget;stays automatic, andsetvalidates and trims. Inside a setter,valueis the value being assigned. - Guard clauses such as
ArgumentException.ThrowIfNullOrWhiteSpace(value)andArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount)(both added in recent .NET versions) throw a descriptive exception, naming the parameter, in one line. Bad input from a caller is a programming error and should fail loudly; expected situations, like a withdrawal that is too large, get aboolresult instead. staticmembers belong to the class, not to any one object, soSavingsAccount.Openedcounts all accounts.override string ToString()replaces the default text for an object (which would be its type name).Console.WriteLine(account)and interpolation both call it.
Primary constructors and initializers
Since C# 12, a class can declare its constructor parameters right after its name: class Circle(double radius). The parameters are in scope throughout the class body and are typically used to initialise properties: public double Radius { get; } = radius;. That style appears in the programs below.
For types with many optional settings, callers can use an object initializer: new Booking { Guest = "Kenji", Nights = 3 } runs the constructor and then sets the named properties. A property declared with init instead of set can be set in an initializer but never afterwards; marking it required (C# 11) makes the compiler insist that every caller sets it.
Classes and structs: references and values
Classes are reference types. A variable of a class type holds a reference to an object on the managed heap, and assigning the variable copies the reference: two variables, one object. Structs are value types. A variable of a struct type holds the data itself, and assigning copies all of it: two variables, two independent values.
// The same shape as a struct (value type) and as a class (reference type).
PointStruct s1 = new(1, 2);
PointStruct s2 = s1; // copies the data
s2.X = 100;
Console.WriteLine($"struct: s1.X = {s1.X}, s2.X = {s2.X}");
PointClass c1 = new(1, 2);
PointClass c2 = c1; // copies the reference
c2.X = 100;
Console.WriteLine($"class: c1.X = {c1.X}, c2.X = {c2.X}");
// Equality: structs compare their fields; classes compare identity by default.
Console.WriteLine($"structs equal? {new PointStruct(3, 4).Equals(new PointStruct(3, 4))}");
Console.WriteLine($"classes equal? {new PointClass(3, 4).Equals(new PointClass(3, 4))}");
struct PointStruct(int x, int y)
{
public int X { get; set; } = x;
public int Y { get; set; } = y;
}
class PointClass(int x, int y)
{
public int X { get; set; } = x;
public int Y { get; set; } = y;
}It prints:
struct: s1.X = 1, s2.X = 100
class: c1.X = 100, c2.X = 100
structs equal? True
classes equal? FalseWhen should you write a struct? Rarely, and deliberately. The .NET design guidelines suggest a struct when the type is small (a few fields, roughly 16 bytes or less), represents a single value (like a point, a colour or a money amount), is immutable, and will not be boxed often. int, double, DateTime, TimeSpan and Guid are all structs. Mark such types readonly struct so the compiler enforces immutability. A mutable struct, like PointStruct above, is a classic source of bugs: change a copy and wonder why the original did not change. The memory lesson returns to why structs matter for performance.
Records: data with value semantics
Much of a program's data is just data: a price, an address, a message from a queue. For such types you want equality by content, a readable ToString, and immutability. Writing that by hand in a class takes dozens of lines. A record (C# 9) gets it from the compiler:
// A positional record: properties, constructor, equality, ToString and Deconstruct in one line.
var price = new Money(1500m, "KES");
var same = new Money(1500m, "KES");
Console.WriteLine(price);
Console.WriteLine($"Equal by value? {price == same}; same object? {ReferenceEquals(price, same)}");
// Records are immutable by default; 'with' makes a modified copy.
var discounted = price with { Amount = price.Amount * 0.9m };
Console.WriteLine($"{price.Amount} -> {discounted.Amount} {discounted.Currency}");
var (amount, currency) = discounted;
Console.WriteLine($"Deconstructed: {amount} and {currency}");
// required + init: set once, in an object initializer, never again.
var booking = new Booking { Guest = "Kenji Watanabe", Nights = 3 };
Console.WriteLine(booking);
var longer = booking with { Nights = 5 };
Console.WriteLine($"{booking.Nights} nights became {longer.Nights}; total {longer.Total(new Money(80m, "EUR"))}");
record Money(decimal Amount, string Currency)
{
public override string ToString() => $"{Amount:N2} {Currency}";
}
record Booking
{
public required string Guest { get; init; }
public required int Nights { get; init; }
public Money Total(Money perNight) => perNight with { Amount = perNight.Amount * Nights };
}It prints:
1,500.00 KES
Equal by value? True; same object? False
1500 -> 1350.0 KES
Deconstructed: 1350.0 and KES
Booking { Guest = Kenji Watanabe, Nights = 3 }
3 nights became 5; total 400.00 EURrecord Money(decimal Amount, string Currency) declares a class with two init-only properties, a constructor, value-based Equals, ==, GetHashCode, a Deconstruct method, and a ToString that lists the properties (as Booking's output shows; Money overrides it). The with expression copies a record and changes some properties, leaving the original untouched: immutability without pain.
Two details in the output deserve a look. 1500m * 0.9m printed as 1350.0: a decimal remembers its scale (the number of digits after the point), and multiplying adds the scales of the operands. And N2 formatted with a comma as thousands separator because of the current culture, as the previous lesson warned.
A plain record is a reference type (you can also write record class). A record struct (C# 10) is a value type with the same conveniences; a readonly record struct is a good default for small immutable values.
Choosing among them
| You are modelling | Reach for | Why |
|---|---|---|
| Something with identity and a life cycle: an account, an order being processed, a connection | class | Two accounts with the same balance are still two accounts; behaviour and invariants matter more than data |
| Data passed between parts of a program: a request, an event, a row from a query, a configuration | record | Value equality, readable ToString, immutability and with for free |
| A small single value created in large numbers: a coordinate, a colour, an amount in one currency | readonly record struct or readonly struct | No heap allocation, copied cheaply, compared by value |
| A family of related kinds handled by one piece of code | abstract record or abstract class with derived types, or an interface | Polymorphism, or pattern matching over the kinds (a later lesson) |
When in doubt between a class and a record, ask whether two instances with identical contents should count as the same thing. If yes, it is a record.
Note
Record equality compares each property with that property's own Equals. If a property is an array or a List<string>, those compare by reference, so two records holding equal-looking arrays are not equal. Exercise 2 shows this. Keep record properties to values, strings, other records, or immutable collections.
Inheritance, and when to avoid it
A class can inherit from one base class, gaining its members and adding or replacing behaviour. Members the base allows to be replaced are virtual; derived classes replace them with override; an abstract member has no implementation and must be overridden; an abstract class cannot be instantiated; and a sealed class cannot be inherited from.
// Inheritance and polymorphism with an abstract base class.
List<Shape> shapes = [new Circle(1.5), new Rectangle(2, 3), new Square(2.5)];
foreach (Shape s in shapes)
{
Console.WriteLine(s.Describe());
}
double total = 0;
foreach (Shape s in shapes) total += s.Area;
Console.WriteLine($"Total area: {total:F2}");
abstract class Shape
{
public abstract double Area { get; }
public virtual string Name => GetType().Name.ToLowerInvariant();
public string Describe() => $"a {Name} with area {Area:F2}";
}
class Circle(double radius) : Shape
{
public double Radius { get; } = radius;
public override double Area => Math.PI * Radius * Radius;
}
class Rectangle(double width, double height) : Shape
{
public double Width { get; } = width;
public double Height { get; } = height;
public override double Area => Width * Height;
}
sealed class Square(double side) : Rectangle(side, side)
{
public override string Name => "square (a special rectangle)";
}It prints:
a circle with area 7.07
a rectangle with area 6.00
a square (a special rectangle) with area 6.25
Total area: 19.32Describe is written once in Shape, yet calls the right Area and Name for each object: that is polymorphism, chosen at run time by the object's actual type. Square passes its arguments to its base class's primary constructor with : Rectangle(side, side).
Inheritance is powerful and easily overused. Deep hierarchies couple classes tightly: a change to a base class ripples into every descendant. Experienced C# developers prefer composition (an object has collaborators, passed into its constructor) and interfaces (the next lesson) for flexibility, and keep inheritance for genuine "is a kind of" relationships within one codebase. Many teams mark classes sealed by default, which also lets the runtime call their methods a little faster.
Organising types in a real project
The programs in this lesson put everything in one file so you can run them with dotnet run. A real project spreads its types out, and a few conventions make large codebases navigable.
One type per file, named after the type. SavingsAccount lives in SavingsAccount.cs. Folders group related types: Accounts/, Payments/, Reports/.
Namespaces give types a full name and avoid clashes between libraries. Modern C# uses a file-scoped namespace declaration (C# 10), one line at the top of the file that applies to everything below it:
namespace Lumenary.Banking.Accounts;
public sealed class SavingsAccount
{
// ...
}Other files then write using Lumenary.Banking.Accounts; to use the type by its short name. By convention, namespaces mirror the folder structure and start with the company or product name.
Visibility is a design tool. Types default to internal: visible inside their own assembly, invisible to other projects. Make a type public only when another project genuinely needs it, because every public member is a promise you will have to keep. Inside a type, keep fields private and expose what callers need through properties and methods.
partial lets one class be split across several files. You will mostly meet it in generated code: tools such as source generators, designers and serialisers write half of a class and leave the other half to you.
A short design checklist
When you create a type, ask:
- What is its invariant? Make the constructor establish it and every public member preserve it. If there is no invariant at all, a record may be all you need.
- Does it need to change after creation? If not, make it immutable (
init,readonly, records). Immutable objects can be shared freely between threads and never surprise anyone. - How should two instances compare? Identity (classes), content (records and structs), or something custom. If you override
Equals, you must overrideGetHashCodeconsistently, or dictionaries and hash sets will misbehave; records do both for you. - Is it meant to be inherited? If you have not designed for it, say so with
sealed. - Who needs to see it? Start
internalandprivate; widen only when a caller needs it.
Common misconceptions
Misconception
"Structs are faster, so I should use them everywhere." Structs avoid a heap allocation, but every assignment and every method argument copies the whole value. Large structs copied often are slower than classes, and mutable structs cause bugs. Use them for small, immutable values.
Misconception
"Records are only for immutable data, so I can't put methods in them." A record is a class (or struct) with generated members; you can add methods, computed properties and validation, as Booking.Total shows. What records change is equality and copying.
Misconception
"Public fields are fine; properties are just ceremony." An auto-property costs one line and nothing at run time (the JIT inlines simple accessors). Changing a public field to a property later is a breaking change for compiled callers, and many libraries ignore fields. Use properties for anything public.
Exercises
1. Classes, structs, records and properties
CoreComputationalWhat does this program print?
static void Move(Counter c) => c.Value += 10;
Counter a = new() { Value = 1 };
Move(a);
Box b = new() { Value = 1 };
Shift(b);
Console.WriteLine($"{a.Value} {b.Value}");
static void Shift(Box box) => box.Value += 10;
struct Counter { public int Value { get; set; } }
class Box { public int Value { get; set; } }
2. Classes, structs, records and properties
StretchComputationalWhat does this program print?
var x = new Team("Lions", ["Ade", "Bo"]);
var y = new Team("Lions", ["Ade", "Bo"]);
var z = x with { };
Console.WriteLine($"{x == y} {x == z}");
record Team(string Name, string[] Players);
3. Classes, structs, records and properties
CoreComputationalWhat does this program print?
Animal pet = new Parrot();
Console.WriteLine($"{pet.Sound()} {pet.Legs}");
class Animal
{
public virtual string Sound() => "...";
public int Legs { get; init; } = 4;
}
class Parrot : Animal
{
public Parrot() { Legs = 2; }
public override string Sound() => "Hello!";
}
4. Classes, structs, records and properties
Warm-upComputationalWhat does this program print?
var p = new Person("Lina", 30);
var q = p with { Age = 31 };
Console.WriteLine(q);
record Person(string Name, int Age);
5. Classes, structs, records and properties
CoreHumanYou need a type for a geographic coordinate: a latitude and a longitude, both double, never changed after creation, created millions of times in a mapping engine, and compared by value. What is the best declaration?
6. Classes, structs, records and properties
CoreHumanGiven record Booking { public required string Guest { get; init; } }, which lines compile? (Choose all that apply.)
Further reading and resources
- Classes, structs and records · MicrosoftThe official overview of C#'s three kinds of user-defined type.
- Properties · MicrosoftAuto-properties, accessors, init and required, and the field keyword.
- Records · MicrosoftExactly what the compiler generates for a record.
- Choosing between class and struct · MicrosoftThe .NET design guidelines' advice, from the people who designed the base class library.