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.
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
6
4
0.3
200Narrower 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.
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
2.3333333333333335
1.5
200
255
too largeYour 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.
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
temperatures: 20C, 30C
words: hiMaking 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.
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
Vec { X = 4, Y = 6 }
3Generic math is mostly for libraries. For application code that only uses one number type, a plain method is much easier to read.
Your turn
Clamp and scale
Write two generic methods:
Clamp<T>(T value, T low, T high), for anyINumber<T>, returns the value limited to the range. Iflowis abovehigh, throwArgumentException.Scale<T>(T value, T fromMax, T toMax), for anyIFloatingPoint<T>, converts a value from a range of 0 tofromMaxinto a range of 0 totoMax. 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:
10
0.5
-1
50
refusedusing 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
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;
}10
0.5
-1
50
refusedCompletion is saved in this browser only. It does not measure mastery.