skip to content

Now that C# interfaces can carry default method bodies, what can a C# abstract class still do that an interface cannot?

level: middleimportance: must knowfreq 78%

answer

  1. state and construction
  2. CS0525 and CS0526
  3. inherited members on the derived type
  4. one base class, many interfaces

basics

~20 s

An abstract class can hold instance fields, run a constructor for every subclass, and pass on members that subclasses call by name. Interfaces cannot, but a type may implement many interfaces and derive from only one class.

solid answer

~40 s

C# 8 let interfaces declare bodies, static members and access modifiers, but not instance state: an instance field is CS0525, an instance constructor CS0526, and `string Name { get; set; }` in an interface is an abstract property, not an auto-property. An abstract class keeps three things an interface lacks: **state** (fields, auto-properties), **construction** (a constructor every subclass must chain to, so invariants are enforced once), and **inheritance of members**, which subclasses call by name, override, seal and reach with `base.`. A default interface method, by contrast, is not inherited: it is callable only through the interface type. The price of an abstract class is the single base-class slot, and structs cannot derive from it at all, while a class or struct can implement any number of interfaces.

code

csharp · 34 lines
csharp
#:property PublishAot=false
PaymentGatewayBase gateway = new CardGateway("merchant-42");
gateway.Charge(19.99m);
Console.WriteLine(FormattableString.Invariant($"default fee {IFeePolicy.DefaultFee}"));

public interface IFeePolicy
{
    static decimal DefaultFee = 0.30m;             // static field: allowed
    decimal Fee(decimal amount) => DefaultFee;     // default body: allowed, but no instance state
    // decimal lastFee;                            // error CS0525: Interfaces cannot contain instance fields
    // IFeePolicy() { }                            // error CS0526: Interfaces cannot contain instance constructors
    // string Name { get; set; } = "";             // error CS8053: no initializers on instance properties
}

public abstract class PaymentGatewayBase : IFeePolicy
{
    private readonly string _merchantId;           // instance state
    protected PaymentGatewayBase(string merchantId) // constructor runs for every subclass
        => _merchantId = merchantId ?? throw new ArgumentNullException(nameof(merchantId));

    public void Charge(decimal amount)             // inherited: callable on any subclass type
    {
        var fee = ((IFeePolicy)this).Fee(amount);
        Send(_merchantId, amount + fee);
    }

    protected abstract void Send(string merchantId, decimal total);
}

public sealed class CardGateway(string merchantId) : PaymentGatewayBase(merchantId)
{
    protected override void Send(string merchantId, decimal total)
        => Console.WriteLine(FormattableString.Invariant($"{merchantId}: {total}"));
}

go deeper

for a junior

Recall the short list: an abstract class can have fields and constructors and is limited to one per class; interfaces cannot hold state but a type can implement many.

for a middle

Name the diagnostics, CS0525 and CS0526, explain that an interface property is abstract, and that default methods are not inherited by the class.

for a senior

Show how the difference decides real designs: constructor-enforced invariants and template methods in a base class, capabilities for structs and existing hierarchies in interfaces.

for a principal

Weigh what each choice commits a published API to: a base class spends every consumer's single inheritance slot, an interface can never enforce construction rules.

## What C# 8 changed, and what it did not Before C# 8 the comparison was simple: an interface declared signatures, an abstract class could also contain code. C# 8 added **default interface methods**, and with them interfaces gained: - members with bodies (methods, properties, indexers, events); - `static` members, including static fields and static methods; - access modifiers on members (a member without one is still `public`); - `sealed` non-virtual members and `private` helper members with bodies. What interfaces still cannot have is **instance state**, and that single rule drives most of the remaining differences. ## What only an abstract class can do 1. **Hold instance state.** An instance field in an interface is error CS0525, "Interfaces cannot contain instance fields". `string Name { get; set; }` inside an interface declares an abstract property each implementer must supply, and giving it an initializer is CS8053. An abstract class can have private fields, auto-properties and `readonly` data. 2. **Run construction logic.** An interface constructor is CS0526, "Interfaces cannot contain instance constructors". An abstract class can declare a `protected` constructor that every subclass must chain to, which is the one place to validate a merchant id or a currency once for all subclasses. 3. **Pass members to subclasses.** Members of a base class are inherited: a subclass calls them by simple name, the subclass's own type exposes them, and `base.Method()` reaches the base version. A default interface method is **not** inherited by the implementing class; it is callable only through an interface-typed reference. 4. **Use the full class toolkit for overriding.** `virtual`, `abstract`, `override`, `sealed override` and `protected` hooks work as they do on any class hierarchy. ## What only an interface can do - **Multiple implementation.** A class has one base class but can implement any number of interfaces. - **Structs.** A struct can implement interfaces but cannot derive from a class: every struct derives implicitly from `System.ValueType`. - **Retrofitting existing types.** A type that already has a base class can still take on an interface. ## Side by side | Capability | Abstract class | Interface (C# 8 and later) | |---|---|---| | Instance fields, auto-properties | yes | no (CS0525) | | Instance constructors | yes | no (CS0526) | | Static fields and methods | yes | yes | | Method bodies | yes | yes, default implementations | | Bodies callable on the implementing type | yes, inherited | no, interface reference only | | How many per type | one base class | any number | | Usable by structs | no | yes | ## Access modifiers on interface members Before C# 8 every interface member was implicitly public and no modifier was allowed. Since C# 8 an interface member may be `public`, `internal`, `protected` or `private`, and one without a modifier is still `public`. A `private` member must have a body and serves as a helper for the interface's own default implementations; a `protected static` helper can be called from derived interfaces and, qualified with the interface name, from implementing classes. This narrows the gap with abstract classes but does not close it: none of these members can store per-instance data. ## Reading the difference in code A typical design combines both. An abstract `PaymentGatewayBase` stores the merchant id, validates it in its constructor and offers a template `Charge` method that calls an abstract `Send`; an `IFeePolicy` interface describes a capability any type can take on, with a default `Fee` body that reads only static data. Each subclass inherits `Charge`, but the default `Fee` body is reached only after converting to `IFeePolicy`. ## Common misreadings - **"Default methods make abstract classes obsolete."** They do not: no interface can enforce construction-time invariants or own state. - **"An interface property is an auto-property."** Inside an interface, `{ get; set; }` declares an abstract member with no storage. - **"Static fields in an interface are per implementer."** A static field declared in an interface belongs to the interface and is shared by everyone, not copied into each implementing type. The choice is then about what the abstraction must guarantee: shared state and construction rules point to an abstract class; a capability that unrelated types, structs or types with an existing base class must offer points to an interface.

  • Does string Name { get; set; } in an interface declare an auto-property?
    No. Inside an interface it declares an abstract property with no storage, which every implementing class or struct must supply. An initializer on it is CS8053, and a default implementation would need explicit accessor bodies that use other members, because the interface has no instance field to store a value in.
  • Why can a struct implement an interface but not derive from an abstract class?
    Every struct implicitly derives from `System.ValueType` and cannot name another base class, so class inheritance is closed to it. Interfaces are the only way to give a struct a shared contract; calling through an interface-typed reference boxes the struct, which matters on hot paths.

  • Since C# 8, interfaces can hold instance fields like an abstract class.
  • Default interface methods make abstract classes obsolete in modern C#.
  • An interface can declare a constructor that every implementer runs.
  • A class inherits default interface methods as its own public members.
  • A class can derive from several abstract classes if none of them has fields.