Lesson 12 of 24

In progress

Course progress

C# and .NET

Classes and objects

Create a class with fields, methods and a constructor, and see how reference semantics change what a method can do to its argument.

A class bundles state and behaviour. C# adds a few conveniences over Java — properties, object initialisers, records — but the core idea is the same, and the details decide how the class behaves when shared.

What you will learn

  • Declare a class with fields, a constructor and methods.
  • Understand reference semantics for objects.
  • Use object initialisers and required members.

A class

public class Basket
{
private readonly List<decimal> prices = new();
public void Add(decimal price)
{
if (price <= 0) throw new ArgumentOutOfRangeException(nameof(price));
prices.Add(price);
}
public decimal Total() => prices.Sum();
public int Count => prices.Count;
}

The list is private and readonly: the field cannot be replaced, and the only way in is Add, which validates. prices.Sum() is a LINQ method, which the using System.Linq implicit import makes available.

public int Count => prices.Count; is an expression-bodied property: a getter with no setter, computed from the state. That is the shape a calculated value should take.

Using it

var basket = new Basket();
basket.Add(250m);
basket.Add(99.50m);
Console.WriteLine($"{basket.Count} items, {basket.Total():F2}");

new Basket() creates the object; the var hides the type name only, not the type. Each new gives a fresh object with its own list.

Reference semantics

var a = new Basket();
a.Add(100m);
var b = a;
b.Add(50m);
Console.WriteLine(a.Total());   // 150

b = a copies the reference, so both variables point at the same object. That is the defining difference from structs and a frequent source of surprise.

A method can change the object it receives:

static void Clear(Basket basket) => basket.Clear();

Calling Clear(basket) empties the caller’s basket, because the method has a reference to the same object. If a method must not do that, take a different type — an IReadOnlyCollection<decimal> instead of a mutable class — so the signature says so.

null is possible for any reference, which is why nullable annotations matter on parameters and return values.

Object initialisers

var order = new Order
{
Customer = "Ana",
Total = 1250m,
PlacedOn = new DateOnly(2025, 2, 14)
};

An initialiser sets properties after the constructor runs. It reads well for data-heavy types, and it allows a parameterless constructor plus named sets.

The risk is that the object exists briefly in an invalid state. required fixes that by making the compiler demand the properties:

public class Order
{
public required string Customer { get; init; }
public required decimal Total { get; init; }
public DateOnly PlacedOn { get; init; }
}

Now new Order { Total = 1m } fails to compile, which is the check you want.

Fields, properties and methods

  • A field is a variable on the object: private decimal total;.
  • A property looks like a field and runs code: public decimal Total { get; private set; }.
  • A method performs an action: public void Add(decimal price).

Public fields are discouraged because they cannot validate or compute, and changing one to a property later is a binary-breaking change for libraries. Start with properties.

Static members

public class Money
{
public static Money Zero { get; } = new(0m);
public decimal Amount { get; }
public Money(decimal amount) => Amount = amount;
}

A static member belongs to the type, not an instance. Money.Zero is created once. Static mutable state is global state: it persists between tests, is shared across threads and makes behaviour depend on execution order. Use static for constants and pure helpers.

Nested types and namespaces

namespace Shop;
public class Order
{
public sealed class Line
{
public required string Sku { get; init; }
public int Quantity { get; init; }
}
}

A nested type is scoped to its container, which is useful when it only makes sense there. File-scoped namespaces (namespace Shop;) remove a level of indentation and are the modern default.

Class design in one paragraph

Keep state private, expose behaviour rather than fields, validate in the constructor, and prefer immutability for values. If a class has fifteen public methods with no shared state, it is a namespace; if it has forty that all touch the same three fields, it may be two classes. The signal is the name: a class that needs "and" in its name describes two responsibilities.

Returning the internal list from a method or property, so a caller can add items without validation. Return IReadOnlyList<T> or a copy.

Write a Playlist class with a private list of track names, Add that rejects duplicates, Remove returning a bool, and a Tracks property returning a read-only view.

Show solution
public class Playlist { private readonly List<string> tracks = new(); public IReadOnlyList<string> Tracks => tracks; public bool Add(string track) { if (string.IsNullOrWhiteSpace(track) || tracks.Contains(track)) return false; tracks.Add(track.Trim()); return true; } public bool Remove(string track) => tracks.Remove(track); public int Count => tracks.Count; }

IReadOnlyList<string> prevents adding through the property while still allowing a caller to iterate. Add reports whether it changed anything, which is more useful than throwing for a duplicate, and the blank check runs before the list is touched.

Recap

  • A class holds private state and exposes behaviour; properties replace public fields.
  • Objects are references, so assigning or passing one shares the object.
  • required and init make object initialisers safe for data-heavy types.

Next, constructors: validating, chaining and the difference between a class and a record.

When should I use a struct?
For small immutable values that behave like numbers, such as a coordinate or a money amount. Classes are the default.
What does sealed do?
It prevents inheritance. Sealing a class is a commitment that its behaviour will not be extended.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.