Skip to content
Happy Programming Guide
Start learning
C#

Object-Oriented Programming (OOP) in C#

Classes, inheritance, interfaces, polymorphism and encapsulation in C# — plus records, and why composition usually beats deep inheritance.

Hands typing on a laptop keyboard

Object-oriented programming organises code around objects that hold data and the operations on it. C# is built on the model, so almost everything you write is inside a class. This guide covers the four ideas people name — encapsulation, inheritance, polymorphism and abstraction — with the C# specifics, and the case for reaching for interfaces and composition before inheritance.

A class#

CSHARP
public class BankAccount
{
    public string Owner { get; }
    public decimal Balance { get; private set; }

    public BankAccount(string owner, decimal opening = 0m)
    {
        if (string.IsNullOrWhiteSpace(owner))
            throw new ArgumentException("Owner is required", nameof(owner));

        Owner = owner;
        Balance = opening;
    }

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(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:C}";
}
CSHARP
var account = new BankAccount("Ana", 100m);
account.Deposit(50m);
Console.WriteLine(account.TryWithdraw(500m));   // False
Console.WriteLine(account);                      // Ana: £150.00

Encapsulation#

Notice what the caller cannot do: set the balance directly. { get; private set; } means the value is readable everywhere and writable only from inside the class. Every change goes through a method that validates it.

CSHARP
account.Balance = 1_000_000m;    // compile error

That is the whole point of encapsulation. It is not about hiding data; it is about controlling the ways it can change, so an object can never be in an invalid state.

Modifier Visible to
public everything
private this class only (the default for members)
protected this class and anything derived from it
internal this assembly
protected internal this assembly, or derived classes elsewhere
private protected derived classes in this assembly

Inheritance#

CSHARP
public abstract class Shape
{
    public string Name { get; }

    protected Shape(string name) => Name = name;

    public abstract double Area();                    // must be implemented

    public virtual string Describe() =>               // may be replaced
        $"{Name} with area {Area():F2}";
}

public class Circle : Shape
{
    public double Radius { get; }

    public Circle(double radius) : base("Circle") => Radius = radius;

    public override double Area() => Math.PI * Radius * Radius;
}

public class Rectangle : Shape
{
    public double Width { get; }
    public double Height { get; }

    public Rectangle(double width, double height) : base("Rectangle")
    {
        Width = width;
        Height = height;
    }

    public override double Area() => Width * Height;

    public override string Describe() =>
        $"{Width} by {Height} rectangle, area {Area():F2}";
}

Three keywords carry the meaning. abstract on a class means it cannot be instantiated; on a method it means derived classes must supply an implementation. virtual means a method has a default that may be replaced. override replaces it.

Polymorphism#

CSHARP
var shapes = new List<Shape>
{
    new Circle(3),
    new Rectangle(4, 5),
};

foreach (var shape in shapes)
{
    Console.WriteLine(shape.Describe());     // the right version each time
}

Console.WriteLine(shapes.Sum(s => s.Area()));

The loop calls one method name and gets different behaviour depending on the actual type. That is polymorphism, and it is what lets you add a Triangle class later without touching this loop at all.

Interfaces#

CSHARP
public interface IExporter
{
    string FileExtension { get; }
    string Export(IEnumerable<Shape> shapes);
}

public class CsvExporter : IExporter
{
    public string FileExtension => "csv";

    public string Export(IEnumerable<Shape> shapes) =>
        string.Join("\n", shapes.Select(s => $"{s.Name},{s.Area():F2}"));
}

public class JsonExporter : IExporter
{
    public string FileExtension => "json";

    public string Export(IEnumerable<Shape> shapes) =>
        JsonSerializer.Serialize(shapes.Select(s => new { s.Name, Area = s.Area() }));
}
CSHARP
public class Report
{
    private readonly IExporter _exporter;

    public Report(IExporter exporter) => _exporter = exporter;

    public void Save(IEnumerable<Shape> shapes, string path) =>
        File.WriteAllText($"{path}.{_exporter.FileExtension}", _exporter.Export(shapes));
}

An interface is a contract with no implementation. A class can inherit one base class but implement any number of interfaces, which is why interfaces are the more flexible tool.

Interface or abstract class#

Interface Abstract class
How many can a class have many one
Can hold state no yes
Can share implementation default methods only yes
Says “can do” “is a”

Rule of thumb: an interface for a capability, an abstract class when derived types genuinely share data and behaviour.

Records#

CSHARP
public record Point(double X, double Y);

var a = new Point(1, 2);
var b = new Point(1, 2);

Console.WriteLine(a == b);          // True - compares values
Console.WriteLine(a);               // Point { X = 1, Y = 2 }
var moved = a with { X = 5 };       // copy with one change

That one line generates a constructor, two properties, equality, hashing, a readable ToString and deconstruction. Use a record when the object is defined by its data; use a class when it has an identity that outlives its values — anything backed by a database row, typically.

Composition over inheritance#

CSHARP
// Inheritance - rigid, and a Robot is not really an Animal
public class Animal { public void Move() { } }
public class Dog : Animal { public void Bark() { } }

// Composition - assemble from capabilities
public interface IMover { void Move(); }
public interface ISpeaker { void Speak(); }

public class Dog : IMover, ISpeaker
{
    private readonly Legs _legs = new();

    public void Move() => _legs.Walk();
    public void Speak() => Console.WriteLine("Woof");
}

Deep inheritance hierarchies become hard to follow, because understanding one class means reading four. A shallow hierarchy with composition inside is easier to change, and it is why most modern guidance favours it.

Static members#

CSHARP
public class Counter
{
    private static int _created;        // shared by every instance

    public int Id { get; }

    public Counter() => Id = ++_created;

    public static int TotalCreated => _created;
}

Static members belong to the type rather than to any instance. Useful for counters, factory methods and utilities — and worth using sparingly, since static state is shared across your whole application and cannot be replaced in a test.

Questions people ask#

What is the difference between a field and a property?

A field stores data; a property is a pair of methods that look like a field. Properties let you add validation or computation later without changing any calling code, which is why public fields are discouraged.

When should I use a struct?

For small, immutable values used in large quantities — a point, a colour. Structs are copied on assignment, so a large one is slower than the class it replaced.

Do I need an interface for everything?

No. An interface with exactly one implementation that never gains a second is pure overhead. Add it when you have a second implementation, or when you need to substitute one in a test.

What does sealed do?

It prevents a class being inherited from. Worth applying when a class was not designed to be extended — it documents the intent and lets the runtime optimise method calls.

Where to go next#

C# design patterns, and which still earn their placeRead next

Keep reading

C#

C# and ASP.NET Core

Building web applications and APIs with ASP.NET Core: minimal APIs, controllers, dependency injection, middleware, validation and configuration.

5 min read

C#

C# Security

The security work that matters in .NET applications: SQL injection, XSS, secrets, authentication, deserialization, randomness and dependency scanning.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *