Static abstract interface members
suggest changeAn ordinary interface describes what you can do with an instance: shape.Area, list.Add(x). Since C# 11 an interface can also require static members: factory methods, constants, parsers and operators. Generic code can then call them on a type parameter:
static T Make<T>(double size) where T : IShapeFactory<T> => T.Create(size);
interface IShapeFactory<TSelf> where TSelf : IShapeFactory<TSelf>
{
static abstract TSelf Create(double size);
}
T.Create(size) calls a static method on whatever type T turns out to be. Before C# 11 the only way to do that was reflection or a separate factory object.
Versions:
- C# 8 (.NET Core 3.0): default implementations for instance interface members, and non-abstract static members in interfaces
- C# 11 (.NET 7):
static abstractandstatic virtualinterface members, including operators - .NET 7: the BCL uses them for
IParsable<T>,ISpanParsable<T>and the generic math interfaces (INumber<T>and friends)
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.
The problem
You can't call a static method on a type parameter. This looks reasonable but doesn't compile:
Console.WriteLine(ParseAll<int>("1 2 3").Sum());
static List<T> ParseAll<T>(string text)
{
var result = new List<T>();
foreach (var part in text.Split(' '))
result.Add(T.Parse(part));
return result;
}
app.cs(7,20): error CS0704: Cannot do non-virtual member lookup in 'T' because it is a type parameter
Constraints used to be able to promise only instance members (where T : IComparable<T>), a base class, or a parameterless constructor (where T : new()). Nothing could promise "T has a static Parse method".
Since .NET 7, int, double, DateOnly, Guid and most other BCL types implement IParsable<T>, which declares static abstract T Parse(string s, IFormatProvider? provider). Add the constraint and T.Parse works:
using System.Globalization;
List<int> ints = ParseAll<int>("1 2 3");
List<double> doubles = ParseAll<double>("1.5 2.25");
List<DateOnly> dates = ParseAll<DateOnly>("2026-10-18 2027-01-01");
Console.WriteLine(ints.Sum());
Console.WriteLine(doubles.Sum());
Console.WriteLine(string.Join(", ", dates.Select(d => d.DayOfWeek)));
static List<T> ParseAll<T>(string text) where T : IParsable<T>
{
var result = new List<T>();
foreach (var part in text.Split(' '))
result.Add(T.Parse(part, CultureInfo.InvariantCulture));
return result;
}
6
3.75
Sunday, Friday
Declaring static abstract members
Mark a static member abstract in an interface and every implementing type must provide it. Methods, properties, events and operators can be static abstract. Fields and constructors can't.
Print<Circle>(1);
Print<Square>(1);
Print<Square>(3);
static void Print<T>(double size) where T : IShape
{
IShape shape = T.Create(size);
Console.WriteLine($"{T.Kind} of size {size}: area {shape.Area:F2}");
}
interface IShape
{
static abstract string Kind { get; }
static abstract IShape Create(double size);
double Area { get; }
}
class Circle(double radius) : IShape
{
public static string Kind => "circle";
public static IShape Create(double size) => new Circle(size);
public double Area => Math.PI * radius * radius;
}
class Square(double side) : IShape
{
public static string Kind => "square";
public static IShape Create(double size) => new Square(size);
public double Area => side * side;
}
circle of size 1: area 3.14
square of size 1: area 1.00
square of size 3: area 9.00
The implementations are ordinary public static members. The abstract keyword appears only in the interface. An interface can mix static abstract members with normal instance members such as Area.
Forget one and the class doesn't compile, the same as for instance members. Adding class Bad : IShape { public double Area => 0; } gives:
error CS0535: 'Bad' does not implement interface member 'IShape.Kind'
error CS0535: 'Bad' does not implement interface member 'IShape.Create(double)'
Only abstract classes can't do this. public static abstract in an abstract class is still an error (CS0112: A static member cannot be marked as 'abstract'). The feature is interface-only.
Where you can call them
A static abstract member has no implementation in the interface, so there's nothing to call on the interface itself. You can reach it only through a type parameter:
var c = IShape.Create(1);
Console.WriteLine(IShape.Kind);
List<IShape> shapes = [];
Print<IShape>(1);
IShape s = new Circle(2);
Console.WriteLine(s.Area);
static void Print<T>(double size) where T : IShape => Console.WriteLine(T.Kind);
// IShape and Circle as above
app.cs(1,9): error CS8926: A static virtual or abstract interface member can be accessed only on a type parameter.
app.cs(2,19): error CS8926: A static virtual or abstract interface member can be accessed only on a type parameter.
app.cs(3,6): error CS8920: The interface 'IShape' cannot be used as type argument. Static member 'IShape.Kind' does not have a most specific implementation in the interface.
app.cs(4,1): error CS8920: The interface 'IShape' cannot be used as type argument. Static member 'IShape.Kind' does not have a most specific implementation in the interface.
Lines 5 and 6 compile: a variable of type IShape is fine. The surprise is line 3. Because List<T> could in theory call T.Kind, an interface with static abstract members can't be a type argument at all, so List<IShape>, Task<IShape> and Dictionary<string, IShape> are all rejected.
The usual fix is to split the interface in two: one with the instance members, used as a normal type, and one with the static members, used as a constraint:
List<IShape> shapes = [Make<Circle>(1), Make<Square>(2), Make<Circle>(0.5)];
foreach (var s in shapes)
Console.WriteLine($"{s.GetType().Name,-6} {s.Area,6:F2}");
Console.WriteLine($"total {shapes.Sum(s => s.Area):F2}");
static T Make<T>(double size) where T : IShapeFactory<T> => T.Create(size);
// instance side: a normal interface, fine in collections
interface IShape
{
double Area { get; }
}
// static side: only usable as a constraint
interface IShapeFactory<TSelf> : IShape where TSelf : IShapeFactory<TSelf>
{
static abstract TSelf Create(double size);
}
class Circle(double radius) : IShapeFactory<Circle>
{
public static Circle Create(double size) => new(size);
public double Area => Math.PI * radius * radius;
}
class Square(double side) : IShapeFactory<Square>
{
public static Square Create(double size) => new(size);
public double Area => side * side;
}
Circle 3.14
Square 4.00
Circle 0.79
total 7.93
The BCL follows the same pattern: IFormattable is an instance interface you can store, while IParsable<T> holds the static Parse.
The TSelf pattern
IShapeFactory<TSelf> where TSelf : IShapeFactory<TSelf> looks circular. It's the curiously recurring template pattern: each type passes itself as the type argument (Circle : IShapeFactory<Circle>). This lets the interface talk about "the implementing type":
CreatereturnsTSelf, soMake<Circle>returns aCircle, not anIShapeFactory.- Operators can take and return the implementing type (see below).
- Default bodies can call other static members through
TSelf.
The constraint is a convention, not a guarantee. A copy-paste mistake compiles:
Circle c = Make<Circle>(1);
Square s = Make<Square>(2);
static T Make<T>(double size) where T : IShapeFactory<T> => T.Create(size);
interface IShapeFactory<TSelf> where TSelf : IShapeFactory<TSelf>
{
static abstract TSelf Create(double size);
}
class Circle : IShapeFactory<Circle>
{
public static Circle Create(double size) => new();
}
// copy-paste mistake: compiles, because Circle satisfies the constraint
class Square : IShapeFactory<Circle>
{
public static Circle Create(double size) => new();
}
app.cs(2,12): error CS0311: The type 'Square' cannot be used as type parameter 'T' in the generic type or method 'Make<T>(double)'. There is no implicit reference conversion from 'Square' to 'IShapeFactory<Square>'.
The class declaration is accepted. The mistake shows up only when generic code tries to use Square, which is usually soon enough.
Static virtual members: defaults
static virtual declares a member with a default body. Implementers may provide their own version, but don't have to. To use other static members from the default body you need TSelf:
Describe<Celsius>();
Describe<Kelvin>();
static void Describe<T>() where T : IUnit<T>
{
Console.WriteLine($"{T.Name,-8} symbol={T.Symbol,-3} {T.Format(21.5)}");
}
interface IUnit<TSelf> where TSelf : IUnit<TSelf>
{
static abstract string Name { get; }
// static virtual: has a default body, implementers may replace it
static virtual string Symbol => TSelf.Name[..1];
static virtual string Format(double value) => $"{value} {TSelf.Symbol}";
}
class Celsius : IUnit<Celsius>
{
public static string Name => "Celsius";
public static string Symbol => "°C";
}
class Kelvin : IUnit<Kelvin>
{
public static string Name => "Kelvin";
}
Celsius symbol=°C 21.5 °C
Kelvin symbol=K 21.5 K
Format calls TSelf.Symbol, so it picks up Celsius's override. Without the type parameter, a default body can't reach the abstract members:
interface IUnit
{
static abstract string Name { get; }
static virtual string Symbol => Name[..1];
}
app.cs(4,37): error CS8926: A static virtual or abstract interface member can be accessed only on a type parameter.
Like default instance methods, the default isn't copied into the class. Celsius.Symbol works because Celsius declares it, but Kelvin.Symbol doesn't exist:
Console.WriteLine(Celsius.Symbol);
Console.WriteLine(Kelvin.Symbol);
app.cs(2,26): error CS0117: 'Kelvin' does not contain a definition for 'Symbol'
You get the default only through a type parameter (T.Symbol with T = Kelvin).
Operators
Interfaces can require operators, which is what makes generic math possible. An operator must take the containing type, or a type parameter constrained to it, so operator interfaces always use TSelf:
Console.WriteLine(Sum<Money>([new(10.50m), new(2.25m), new(7m)]));
Console.WriteLine(Sum<Vec2>([new(1, 2), new(3, 4)]));
static T Sum<T>(IEnumerable<T> items) where T : IAddable<T>
{
T total = T.Zero;
foreach (var item in items) total += item;
return total;
}
interface IAddable<TSelf> where TSelf : IAddable<TSelf>
{
static abstract TSelf Zero { get; }
static abstract TSelf operator +(TSelf left, TSelf right);
}
readonly record struct Money(decimal Amount) : IAddable<Money>
{
public static Money Zero => new(0);
public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);
public override string ToString() => $"${Amount:F2}";
}
readonly record struct Vec2(double X, double Y) : IAddable<Vec2>
{
public static Vec2 Zero => default;
public static Vec2 operator +(Vec2 a, Vec2 b) => new(a.X + b.X, a.Y + b.Y);
}
$19.75
Vec2 { X = 4, Y = 6 }
total += item compiles because + is declared on the constraint. += comes for free from +.
Leave out the where TSelf : IAddable<TSelf> constraint and the operator declaration is rejected:
app.cs(7,32): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.
Use the built-in interfaces
You rarely need to write IAddable yourself. System.Numerics has one interface per operator (IAdditionOperators<TSelf, TOther, TResult>, IMultiplyOperators<...>, IComparisonOperators<...>) and per constant (IAdditiveIdentity<TSelf, TResult> for zero, IMultiplicativeIdentity for one). The built-in number types implement all of them, so a method constrained on them accepts int, double and your own type:
using System.Numerics;
Money[] prices = [new(10.50m), new(2.25m), new(7m)];
Console.WriteLine(Total(prices));
Console.WriteLine(Total([1, 2, 3]));
Console.WriteLine(Total([0.5, 0.25]));
// works for int, double, decimal... and Money
static T Total<T>(IEnumerable<T> items)
where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>
{
T total = T.AdditiveIdentity;
foreach (var item in items) total += item;
return total;
}
readonly record struct Money(decimal Amount)
: IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money>
{
public static Money AdditiveIdentity => new(0);
public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);
public override string ToString() => $"${Amount:F2}";
}
$19.75
6
0.75
For numeric code, constrain on INumber<T> instead of listing operators one by one. The "Generic math" section of Math covers INumber<T>, T.Zero, CreateChecked and the function interfaces like IRootFunctions<T>.
Implementing IParsable and ISpanParsable
Implement IParsable<T> on your own types and they work with every generic parsing helper. ISpanParsable<T> adds ReadOnlySpan<char> overloads, so you can parse slices of a larger string without allocating substrings. It extends IParsable<T>, so you implement four static methods: write the span versions and forward the string versions to them:
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
var orange = Rgb.Parse("#ff8800", null);
Console.WriteLine(orange);
List<Rgb> palette = ParseList<Rgb>("#000000,#FFFFFF,#1e90ff");
Console.WriteLine(string.Join(" | ", palette));
foreach (var input in new[] { "#00ff00", "green", "#12345" })
{
if (TryGet<Rgb>(input, out var c)) Console.WriteLine($"{input}: {c}");
else Console.WriteLine($"{input}: invalid");
}
Console.WriteLine(TryGet<int>("42", out var n) ? n * 2 : -1);
Console.WriteLine(TryGet<Guid>("not-a-guid", out _));
static List<T> ParseList<T>(string text) where T : ISpanParsable<T>
{
var result = new List<T>();
ReadOnlySpan<char> span = text;
foreach (var range in span.Split(','))
result.Add(T.Parse(span[range], CultureInfo.InvariantCulture));
return result;
}
static bool TryGet<T>(string s, [MaybeNullWhen(false)] out T value) where T : IParsable<T> =>
T.TryParse(s, CultureInfo.InvariantCulture, out value);
readonly record struct Rgb(byte R, byte G, byte B) : ISpanParsable<Rgb>
{
public static Rgb Parse(ReadOnlySpan<char> s, IFormatProvider? provider) =>
TryParse(s, provider, out var result)
? result
: throw new FormatException($"'{s}' is not a #rrggbb color");
public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out Rgb result)
{
result = default;
if (s.Length != 7 || s[0] != '#') return false;
if (!byte.TryParse(s[1..3], NumberStyles.HexNumber, null, out var r) ||
!byte.TryParse(s[3..5], NumberStyles.HexNumber, null, out var g) ||
!byte.TryParse(s[5..7], NumberStyles.HexNumber, null, out var b))
return false;
result = new Rgb(r, g, b);
return true;
}
// the string overloads required by IParsable<Rgb> forward to the span versions
public static Rgb Parse(string s, IFormatProvider? provider) => Parse(s.AsSpan(), provider);
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out Rgb result) =>
TryParse(s.AsSpan(), provider, out result);
public override string ToString() => $"rgb({R}, {G}, {B})";
}
rgb(255, 136, 0)
rgb(0, 0, 0) | rgb(255, 255, 255) | rgb(30, 144, 255)
#00ff00: rgb(0, 255, 0)
green: invalid
#12345: invalid
84
False
The same TryGet<T> handles Rgb, int and Guid. Notes:
[MaybeNullWhen(false)]on the genericoutparameter tells the nullable analysis thatvalueis only meaningful when the method returnstrue. The interface declares itsoutparameter the same way.Rgb.Parse(...)can be called directly, because it's a real static method onRgb. The interface only adds the ability to call it throughT.- ASP.NET Core minimal APIs look for a static
TryParsemethod when binding route and query parameters, so a type implementingIParsable<T>can be used as an endpoint parameter (app.MapGet("/color/{c}", (Rgb c) => ...)).
Explicit implementation
As with instance members, you can implement a static member explicitly. It then doesn't appear on the type and can be reached only through the interface constraint:
Console.WriteLine(DefaultOf<Settings>());
Console.WriteLine(DefaultOf<Settings>().Retries);
static T DefaultOf<T>() where T : IHasDefault<T> => T.Default;
interface IHasDefault<TSelf> where TSelf : IHasDefault<TSelf>
{
static abstract TSelf Default { get; }
}
record Settings(int Retries, TimeSpan Timeout) : IHasDefault<Settings>
{
static Settings IHasDefault<Settings>.Default { get; } = new(3, TimeSpan.FromSeconds(30));
}
Settings { Retries = 3, Timeout = 00:00:30 }
3
Settings.Default doesn't compile (CS0117: 'Settings' does not contain a definition for 'Default'). Use this when the static member exists to satisfy a generic API and shouldn't clutter the type's public surface. Explicit implementations have no access modifier, and this one shows that an explicitly implemented static property can have an initializer.
Practical example: a type registry
Static abstract members are handy when each type carries metadata about itself (a name, a version, a message id) and a factory. Here every command declares its name and usage and knows how to build itself from arguments. Registering a command is a single generic call, with no reflection and no attributes:
var registry = new CommandRegistry()
.Register<Echo>()
.Register<Add>()
.Register<Upper>();
Console.WriteLine(registry.Help());
foreach (var line in new[] { "echo hello world", "add 2 40", "upper shout", "rm -rf /" })
Console.WriteLine($"> {line}\n{registry.Run(line)}");
interface ICommand
{
string Execute();
}
interface ICommand<TSelf> : ICommand where TSelf : ICommand<TSelf>
{
static abstract string Name { get; }
static abstract string Usage { get; }
static abstract TSelf Create(string[] args);
}
class CommandRegistry
{
private readonly Dictionary<string, Func<string[], ICommand>> _factories = [];
private readonly List<string> _usage = [];
public CommandRegistry Register<T>() where T : ICommand<T>
{
_factories[T.Name] = args => T.Create(args);
_usage.Add($" {T.Name,-6} {T.Usage}");
return this;
}
public string Help() => "commands:\n" + string.Join('\n', _usage);
public string Run(string line)
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
return _factories.TryGetValue(parts[0], out var create)
? create(parts[1..]).Execute()
: $"unknown command '{parts[0]}'";
}
}
class Echo(string[] words) : ICommand<Echo>
{
public static string Name => "echo";
public static string Usage => "<words...>";
public static Echo Create(string[] args) => new(args);
public string Execute() => string.Join(' ', words);
}
class Add(int a, int b) : ICommand<Add>
{
public static string Name => "add";
public static string Usage => "<a> <b>";
public static Add Create(string[] args) => new(int.Parse(args[0]), int.Parse(args[1]));
public string Execute() => (a + b).ToString();
}
class Upper(string text) : ICommand<Upper>
{
public static string Name => "upper";
public static string Usage => "<text>";
public static Upper Create(string[] args) => new(args[0]);
public string Execute() => text.ToUpperInvariant();
}
commands:
echo <words...>
add <a> <b>
upper <text>
> echo hello world
hello world
> add 2 40
42
> upper shout
SHOUT
> rm -rf /
unknown command 'rm'
This uses the split described earlier: the dictionary stores the plain ICommand interface, and ICommand<TSelf> is used only as the constraint on Register<T>. The lambda args => T.Create(args) captures the concrete T, which turns the compile-time type into a runtime factory. Unlike a reflection-based registry, it works with Native AOT and trimming, and a command that forgets Name or Create doesn't compile.
Gotchas
Static members aren't polymorphic over inheritance. The type argument decides which implementation runs, and a derived class that only hides the member with new doesn't change that:
Console.WriteLine(NameOf<Animal>());
Console.WriteLine(NameOf<Dog>());
static string NameOf<T>() where T : INamed => T.Name;
interface INamed
{
static abstract string Name { get; }
}
class Animal : INamed
{
public static string Name => "animal";
}
class Dog : Animal
{
public static new string Name => "dog";
}
animal
animal
Dog inherits Animal's implementation of INamed, and Animal.Name is what satisfies it. Re-implementing the interface (class Dog : Animal, INamed) makes NameOf<Dog>() return "dog".
Extensions can't satisfy the constraint. C# 14 extension members can add static members to a type you don't own, but they don't make the type implement an interface. A static extension property int.Name doesn't make int an INamed<int>:
Console.WriteLine(Name<int>());
static string Name<T>() where T : INamed<T> => T.Name;
interface INamed<TSelf> where TSelf : INamed<TSelf>
{
static abstract string Name { get; }
}
static class Ext
{
extension(int)
{
public static string Name => "int";
}
}
app.cs(1,19): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Name<T>()'. There is no boxing conversion from 'int' to 'INamed<int>'.
If you don't own the type, write a small wrapper struct that implements the interface.
Generic code over structs is fast. The JIT compiles a separate copy of a generic method for each value-type argument, so T.Create, T.Parse and T.operator + become direct calls (often inlined) with no boxing and no virtual dispatch. That's why the BCL could build generic math on this feature without slowing down int arithmetic.
When to use it
Use static abstract interface members when generic code needs something from the type rather than from an instance:
- parsing and creation:
T.Parse,T.TryParse,T.Create(...); prefer the built-inIParsable<T>/ISpanParsable<T>over your own interface - constants and identities:
T.Zero,T.Empty,T.Default,T.Name - operators: generic algorithms over numbers, vectors, money; prefer the
System.Numericsinterfaces - per-type metadata and factories: registries, serializers, message dispatch, without reflection
If an instance is always at hand, an ordinary instance interface member is simpler. For more on constraints, see Generics, and the Interfaces chapter for interface basics and explicit implementation.