Skip to content

Static Abstract Members and Generic Math

The Course
•
25 min study

For a long time, C# couldn't express "a method that adds any kind of number". An interface could only require instance members, and + is static. Static abstract members changed that, and .NET's number types now implement interfaces such as INumber<T>.

Generic math

INumber<T> requires everything a number can do, including +, comparisons and T.Zero. Sum below is one method, and it runs at full speed for each type. There's no boxing, because each value type gets its own specialized version.

One Sum for all numbers C#
using System.Numerics;

Console.WriteLine(Sum(new[] { 1, 2, 3 }));
Console.WriteLine(Sum(new[] { 1.5, 2.5 }));
Console.WriteLine(Sum(new[] { 0.1m, 0.2m }));
Console.WriteLine(Sum(new byte[] { 100, 100 }));

static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
{
    T total = T.Zero;
    foreach (T value in values)
    {
        total += value;
    }
    return total;
}
Check your prediction
Text
6
4
0.3
200

Narrower interfaces

Require only what you need. IAdditionOperators is enough for +, and IFloatingPoint<T> adds things like Round. T.CreateChecked converts between number types and throws if the value doesn't fit. That's useful for dividing a sum by a count of a different type.

Conversions between number types C#
using System.Numerics;

Console.WriteLine(Average(new[] { 1.0, 2.0, 4.0 }));
Console.WriteLine(Average(new[] { 1m, 2m }));

Console.WriteLine(byte.CreateChecked(200));
Console.WriteLine(byte.CreateSaturating(300));

try
{
    Console.WriteLine(byte.CreateChecked(300));
}
catch (OverflowException)
{
    Console.WriteLine("too large");
}

static T Average<T>(IReadOnlyList<T> values) where T : IFloatingPoint<T>
{
    T total = T.Zero;
    foreach (T value in values)
    {
        total += value;
    }
    return total / T.CreateChecked(values.Count);
}
Check your prediction
Text
2.3333333333333335
1.5
200
255
too large

Your own static abstract members

Any interface can require static members. That lets generic code ask a type for something, without needing an instance. Here, each type knows how to parse itself, and it has a name. T.Parse is resolved for the type that the caller chose.

Asking the type itself C#
Console.WriteLine(ReadAll<Celsius>(new[] { "20", "bad", "30" }));
Console.WriteLine(ReadAll<Word>(new[] { "hi", "" }));

static string ReadAll<T>(string[] lines) where T : IReadable<T>
{
    var good = new List<T>();
    foreach (string line in lines)
    {
        if (T.TryRead(line, out T value))
        {
            good.Add(value);
        }
    }
    return $"{T.Label}: {string.Join(", ", good)}";
}

interface IReadable<T>
{
    static abstract string Label { get; }
    static abstract bool TryRead(string text, out T value);
}

readonly record struct Celsius(int Degrees) : IReadable<Celsius>
{
    public static string Label => "temperatures";

    public static bool TryRead(string text, out Celsius value)
    {
        bool good = int.TryParse(text, out int degrees);
        value = new Celsius(degrees);
        return good;
    }

    public override string ToString() => $"{Degrees}C";
}

readonly record struct Word(string Text) : IReadable<Word>
{
    public static string Label => "words";

    public static bool TryRead(string text, out Word value)
    {
        value = new Word(text);
        return text.Length > 0;
    }

    public override string ToString() => Text;
}
Check your prediction
Text
temperatures: 20C, 30C
words: hi

Making your type a number

By implementing small operator interfaces, your own types work with generic algorithms. This is why the interfaces come in small pieces: implementing all of INumber<T> would be a lot of work. IAdditiveIdentity supplies a zero.

A custom type in a generic method C#
using System.Numerics;

var points = new[] { new Vec(1, 2), new Vec(3, 4) };
Console.WriteLine(Total(points));
Console.WriteLine(Total(new[] { 1, 2 }));

static T Total<T>(IEnumerable<T> values) where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>
{
    T total = T.AdditiveIdentity;
    foreach (T value in values)
    {
        total += value;
    }
    return total;
}

readonly record struct Vec(int X, int Y) : IAdditionOperators<Vec, Vec, Vec>, IAdditiveIdentity<Vec, Vec>
{
    public static Vec operator +(Vec left, Vec right) => new Vec(left.X + right.X, left.Y + right.Y);

    public static Vec AdditiveIdentity => new Vec(0, 0);
}
Check your prediction
Text
Vec { X = 4, Y = 6 }
3

Generic math is mostly for libraries. For application code that only uses one number type, a plain method is much easier to read.

Your turn

Exercise

Clamp and scale

Write two generic methods:

  • Clamp<T>(T value, T low, T high), for any INumber<T>, returns the value limited to the range. If low is above high, throw ArgumentException.
  • Scale<T>(T value, T fromMax, T toMax), for any IFloatingPoint<T>, converts a value from a range of 0 to fromMax into a range of 0 to toMax. For example, 5 from 10 to 100 gives 50.

Print Clamp for 15 between 0 and 10 with int, 0.5 between 0 and 1 with double, and -3m between -1m and 1m with decimal. Print Scale(5.0, 10.0, 100.0). Finally, show that a reversed range is refused.

When it works, it prints:

Text
10
0.5
-1
50
refused
Your workspace C#
using System.Numerics;

Console.WriteLine("Start here");
Hint 1: the idea

INumber<T> includes comparison operators and arithmetic, so the method bodies look just as they would for int.

Hint 2: a first step

Write Clamp with two if statements. T is inferred from the arguments, so make sure that all three have the same type at the call.

Show one solution
C#
using System.Numerics;

Console.WriteLine(Clamp(15, 0, 10));
Console.WriteLine(Clamp(0.5, 0.0, 1.0));
Console.WriteLine(Clamp(-3m, -1m, 1m));
Console.WriteLine(Scale(5.0, 10.0, 100.0));

try
{
    Clamp(1, 10, 0);
}
catch (ArgumentException)
{
    Console.WriteLine("refused");
}

static T Clamp<T>(T value, T low, T high) where T : INumber<T>
{
    if (low > high)
    {
        throw new ArgumentException("low is above high");
    }
    return value < low ? low : value > high ? high : value;
}

static T Scale<T>(T value, T fromMax, T toMax) where T : IFloatingPoint<T>
{
    return value / fromMax * toMax;
}
Text
10
0.5
-1
50
refused

Was this article helpful?

Your response is saved on this device.