Skip to content

Static interface members C# 11.0correctnesstype safety

Allow members of an interface to be static abstract or virtual.

Interfaces have always been a way to define a contract that classes must implement. Since C# 8.0 they could also contain static members with implementations, but there was no way to require implementing types to provide a static member.

In C# 11.0, you can now define static abstract or virtual members on an interface and call them through a type parameter.

Code ​

csharp
public interface IConcatable<T> where T : IConcatable<T>
{
    static abstract T Empty { get; }
    static abstract T Concat(T a, T b);
}

static T ConcatAll<T>(IEnumerable<T> items) where T : IConcatable<T>
{
    T result = T.Empty;
    foreach (var item in items)
        result = T.Concat(result, item);
    return result;
}
csharp
public interface IConcatable<T> where T : IConcatable<T>
{
    T Concat(T other);
}

// No way to ask T for an empty value, so the caller must supply one
static T ConcatAll<T>(T empty, IEnumerable<T> items) where T : IConcatable<T>
{
    T result = empty;
    foreach (var item in items)
        result = result.Concat(item);
    return result;
}

Notes ​

  • static abstract members are only callable through a type parameter constrained to the interface; calling one on the interface type itself is CS8926
  • static virtual gives a default implementation that an implementing type may override, whereas static abstract requires one
  • Interfaces with static abstract members cannot be used as a type argument unless the type parameter is constrained to that interface, and cannot be used as a normal variable type for the static part
  • This is what makes generic math possible: where T : IAdditionOperators<T, T, T> lets you write sum += item over any numeric type without boxing
  • Combined with default interface methods C# 8.0, an interface can now carry both instance and static behaviour
  • The recursive constraint where T : IConcatable<T> is required so that the interface can refer to its own implementing type

More information ​

Powered by Intracia