Tools
Log in
English

Learn to codeC#

C# abstraction

Based on C# 12interface default method · C# 8+

C# interface vs abstract class, default interface methods and a backup example.

In one line

Agree first on a promise, "this can do that job", and leave how it is done to the implementing classes. C# writes this with interface and abstract class.

Why you need it

If the caller has to know every backup style, compressed, plain copy, and the cloud one coming later, each new style means changing the calling code too.

Let the caller know only the IBackup contract, write the shared steps once in FileBackup, and a new style only fills in Pack.

Everyday picture

Think of a parcel form. It has fixed boxes for recipient, weight and address (the interface), and any courier who fills them in can take the parcel. A big courier also keeps a work guide with the order of packing, weighing and shipping (the abstract class), and each branch changes only how it packs.

Example code

Program.cs · 55 lines
IBackup[] jobs = [new ZipBackup(), new MirrorBackup()];string[] files = ["a.txt:1200", "photo.jpg:5000", "notes.md:300"];foreach (IBackup job in jobs){    int bytes = job.Run(files);    Console.WriteLine(job.Summary(bytes));} interface IBackup{    string Name { get; }    int Run(string[] files);     string Summary(int bytes)    {        return $"{Name}: {bytes} bytes";    }} abstract class FileBackup : IBackup{    public abstract string Name { get; }     public int Run(string[] files)    {        int total = 0;        foreach (string f in files)        {            int size = int.Parse(f.Split(':')[1]);            total += Pack(size);        }        return total;    }     protected abstract int Pack(int size);} class ZipBackup : FileBackup{    public override string Name => "zip";     protected override int Pack(int size) => size * 40 / 100;} class MirrorBackup : FileBackup, IBackup{    public override string Name => "mirror";     protected override int Pack(int size) => size;     public string Summary(int bytes)    {        return $"{Name}: {bytes} bytes, copied 1:1";    }}

interface vs abstract class

interfaceabstract class
Can use severalOX
Per-object fieldsXO
ConstructorsXO
Methods with a bodyOO
Default member accesspublicprivate
Create directly with newXX

Interface methods with a body (default implementations) arrived in C# 8, and they are visible only through the interface type.

When to use it

  • A job can be done several ways and callers should not care which
  • Several implementations follow the same steps and differ in one or two (blank methods in an abstract class)
  • Tests need to plug in a fake instead of the real thing (dependency injection on the structure page)

Start with a single interface. Add an abstract class once the implementations begin to repeat code.

By C# convention, interface names start with a capital I, as in IBackup.

Common mistakes

Creating an abstract class with new

An abstract class has an unfinished method (Pack), so it cannot become an object by itself. Create one of the children that fill in the gap.

Wrong

var job = new FileBackup();

What the C# compiler sayserror CS0144: Cannot create an instance of the abstract type or interface 'FileBackup'

Fixed

FileBackup job = new ZipBackup();Console.WriteLine(job.Name);

When you run itzip

Calling a default interface method through the class type

A default implementation lives in the interface; the class does not inherit it. With var, the variable is a ZipBackup and Summary is invisible. Type the variable as IBackup and it appears.

Wrong

var zip = new ZipBackup();Console.WriteLine(zip.Summary(10));

What the C# compiler sayserror CS1061: 'ZipBackup' does not contain a definition for 'Summary' and no accessible extension method 'Summary' accepting a first argument of type 'ZipBackup' could be found (are you missing a using directive or an assembly reference?)

Fixed

IBackup zip = new ZipBackup();Console.WriteLine(zip.Summary(10));

When you run itzip: 10 bytes

Forgetting one abstract member

A child must override every abstract member of its parent; leave one out and it does not compile. If the gap is intentional, make the child abstract too.

Wrong

class TarBackup : FileBackup{    public override string Name => "tar";}

What the C# compiler sayserror CS0534: 'TarBackup' does not implement inherited abstract member 'FileBackup.Pack(int)'

Fixed

class TarBackup : FileBackup{    public override string Name => "tar";     protected override int Pack(int size) => size * 90 / 100;}

Check yourself

Question 1

One 1000-byte file goes through ZipBackup. What is printed?

IBackup job = new ZipBackup();Console.WriteLine(job.Summary(job.Run(["x.log:1000"])));

Show the answer

Answer: 2. zip: 400 bytes Pack shrinks it to 40 percent, 400, and since ZipBackup has no Summary, the interface default text is used.

Question 2

Can an interface declare a field such as int count;?

Show the answer

Answer: 2. It does not compile An interface is a contract, so it cannot hold per-object fields. Declare a property such as int Count { get; } and let the implementing class store the value.

Questions people ask

Should I start with an interface or an abstract class?

Start with an interface when you only name the job. Add an abstract class once implementations share steps and fields. A class can implement many interfaces.

Can an interface have a method with a body?

Since C# 8, interfaces can have default implementations. Those methods are visible only through the interface type, and interfaces still cannot hold per-object fields.

Why do interface names start with I?

It is the C# convention, as in IBackup or IDisposable, so the name alone tells you it is an interface. The compiler does not enforce it.