Default interface members

A default member

Since C# 8 an interface member may have a body. The body is used by every implementation that does not provide its own, so a new member can be added to a published interface without breaking the classes that implement it. This is the feature that made it possible to add methods to IEnumerable<T> and IList<T> in later .NET versions.

IShape square = new Square(3); IShape circle = new Circle(1); Console.WriteLine(square.Describe()); Console.WriteLine(circle.Describe()); interface IShape { string Name { get; } double Area { get; } string Describe() => $"{Name} has area {Area:F2}"; } class Square(double side) : IShape { public string Name => "square"; public double Area => side * side; } class Circle(double radius) : IShape { public string Name => "circle"; public double Area => Math.PI * radius * radius; }

dotnet run

square has area 9.00
circle has area 3.14

Neither class mentions Describe, and both got it: the body that runs is the one in the interface, and it reads the two abstract properties of the object it was called on. A class that wants a different text writes its own Describe and the interface body steps aside.

Static abstract members

C# 11 allows an interface to declare a static abstract member, which a type must implement statically. The point is not the interface itself but the constraint it makes possible: a generic method can require an operator or a constant, and the compiler resolves it for each type. The BCL carries the interfaces for numbers in System.Numerics:

using System.Numerics; Console.WriteLine(Sum(1, 2, 3, 4)); Console.WriteLine(Sum(1.5, 2.25, 0.25)); Console.WriteLine(Sum(10m, 2.5m)); static T Sum<T>(params T[] values) where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T> { var total = T.AdditiveIdentity; foreach (var value in values) { total += value; } return total; }

dotnet run

10
4
12.5

One method body served int, double and decimal, which before C# 11 was three copies of the same loop or a dynamic call. += is the operator interface applied at compile time to the concrete type. Sum(1.5, 2.25, 0.25) is exactly 4, so the double line prints 4 with no decimal point.

The member is not on the class

A default member belongs to the interface, not to the class. It is reachable only through a reference of the interface type, and calling it on the class is a compile error:

var square = new Square(3); Console.WriteLine(square.Describe()); interface IShape { string Name { get; } string Describe() => $"a {Name}"; } class Square(double side) : IShape { public string Name => "square"; public double Side => side; }

dotnet build

Program.cs(2,26): error CS1061: 'Square' does not contain a definition for 'Describe' and no accessible extension method 'Describe' accepting a first argument of type 'Square' could be found (are you missing a using directive or an assembly reference?)

Build FAILED.

Program.cs(2,26): error CS1061: 'Square' does not contain a definition for 'Describe' and no accessible extension method 'Describe' accepting a first argument of type 'Square' could be found (are you missing a using directive or an assembly reference?)
0 Warning(s)
1 Error(s)

Time Elapsed 00:00:11.46

The message offers the two other routes it knows: an extension method on Square, or a using of a namespace that has one. The fix in this program is the declaration IShape square = new Square(3) of the first part. A class may also implement the member explicitly to get both, one for the interface and one on the type.

Rules and when to use it

Exercises

  1. Give Describe a different body in Circle and print both shapes through the interface.
  2. Add a second default member that returns whether the area is above a limit, and call it through IShape.
  3. Write Product<T> with IMultiplyOperators and IMultiplicativeIdentity next to Sum.
  4. Implement Describe on Square as an explicit interface member and call it on the class.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which implementation of a default interface member runs?

    Answer

    The class one if it exists, otherwise the interface body

    The default is a fallback, and an implementation in the class takes precedence.

  2. How is a default member reached?

    Answer

    Through a reference of the interface type

    The member is not part of the class surface, which is why CS1061 appears on the class type.

  3. What does this program print? IShape s = new Box(); Console.WriteLine(s.Describe()); interface IShape { string Name => "box"; string Describe() => $"a {Name}"; } class Box : IShape { }

    Answer

    a box

    Both members are default members of the interface, and Box needs to implement neither.

  4. What is a static abstract interface member for?

    Answer

    It lets a generic constraint require an operator or a constant

    The generic method resolves the operator on the concrete type, which is how generic math works.

  5. What does T.AdditiveIdentity require of T?

    Answer

    That T implements IAdditiveIdentity<T, T>

    The constraint brings the static member into scope, and the type supplies its own value.

  6. What does this program print? Console.WriteLine(Sum(1.5, 2.5)); static T Sum<T>(params T[] v) where T : System.Numerics.IAdditionOperators<T, T, T>, System.Numerics.IAdditiveIdentity<T, T> { var t = T.AdditiveIdentity; foreach (var x in v) t += x; return t; }

    Answer

    4

    The sum is exactly four, and a double four prints without a decimal point.

  7. Why was the feature added to C#?

    Answer

    So a published interface can gain a member without breaking implementers

    An interface in a library cannot be changed without this, because every implementer would fail to compile.

  8. Which member may a default body not use directly?

    Answer

    An instance field, because an interface has none

    An interface holds no instance state, so the body works through the abstract members.

  9. What does CS1061 report in the third program?

    Answer

    The class has no such member and no extension method was found

    The default member exists only on the interface, so the class type has no Describe.

  10. When is a base class still better than a default member?

    Answer

    When the shared part needs state or a constructor

    An interface cannot hold instance state, so shared state needs a class.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev