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.
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 = newZipBackup();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 = newZipBackup();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.
Answer: 2. zip: 400 bytesPack 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.