skip to content

Generic Math Interfaces

Interfaces can declare static abstract members, which powers generic math through INumber<T> and parsing through IParsable<T>. Interviewers ask what problem it solves.

on this pageshow

explore

questions

6

In C#, how does IParsable<T> let a generic ParseSamples<T>(string[] cells) parse int, double or decimal statistics samples, and what must it pass?

level: middleimportance: should knowfreq 35%

answer

  1. a static method turned into a requirement
  2. T.Parse and T.TryParse
  3. the IFormatProvider argument
  4. null means the current culture
  5. a span overload for slices

basics

~10 s

IParsable<T> (.NET 7) declares static abstract Parse(string, IFormatProvider?) and TryParse, so ParseSamples<T> calls T.Parse(cell, provider) and each type parses itself. For machine data it must pass CultureInfo.InvariantCulture: a null provider means the current culture.

solid answer

~40 s

`IParsable<TSelf>` turns the familiar static `Parse` and `TryParse` into interface requirements: `static abstract TSelf Parse(string s, IFormatProvider? provider)` and `static abstract bool TryParse(string? s, IFormatProvider? provider, out TSelf result)`. With `where T : IParsable<T>`, the method writes `T.Parse(cell, provider)` and `int`, `double`, `decimal`, `Guid` or `DateTime` supply their own parser; a type that does not implement it, such as `Uri`, is rejected at compile time with CS0311. The provider is the trap: for numeric types `null` means the current culture, so on a de-DE server `double` parses `"3.5"` as 35, because the dot is a group separator there. Pass `CultureInfo.InvariantCulture` for files and protocols. `ISpanParsable<T>` adds `ReadOnlySpan<char>` overloads for parsing a slice without a substring, and `INumberBase<T>` already inherits it, so an `INumber<T>` constraint gives you `T.Parse` too.

code

csharp · 21 lines
csharp
using System.Globalization;

string[] cells = ["3.5", "4.25", "5"];
CultureInfo.CurrentCulture = new CultureInfo("de-DE");   // ',' is the decimal separator

double[] wrong = ParseSamples<double>(cells, provider: null);
double[] right = ParseSamples<double>(cells, CultureInfo.InvariantCulture);
Console.WriteLine(string.Join(" ", wrong.Select(d => d.ToString(CultureInfo.InvariantCulture))));
Console.WriteLine(string.Join(" ", right.Select(d => d.ToString(CultureInfo.InvariantCulture))));
Console.WriteLine(TryParseSample<int>("12x", out int n) + " " + n);

static T[] ParseSamples<T>(string[] cells, IFormatProvider? provider) where T : IParsable<T>
{
    var result = new T[cells.Length];
    for (int i = 0; i < cells.Length; i++)
        result[i] = T.Parse(cells[i], provider);
    return result;
}

static bool TryParseSample<T>(string? cell, out T? value) where T : IParsable<T>
    => T.TryParse(cell, CultureInfo.InvariantCulture, out value);

go deeper

for a junior

Recall that IParsable<T> gives generic code T.Parse and T.TryParse, and that int, double, decimal, Guid and DateTime all implement it.

for a middle

Explain the two static abstract members, why the provider argument matters, and how ISpanParsable<T> parses a slice without allocating substrings.

for a senior

Show that you would catch a null provider in review, pass the invariant culture for machine data, and know a missing implementation is a compile-time CS0311.

for a principal

Decide the parsing rule for the codebase: which inputs are machine data parsed with the invariant culture, and which are user input parsed with an explicit culture.

## Why parsing needed an interface `int.Parse`, `double.Parse` and `Guid.Parse` have always existed, but they are **static** methods with no shared contract, so a generic method could not call "`T`'s parse". Before .NET 7, generic parsing meant one of these workarounds: - `Convert.ChangeType(text, typeof(T))`, which returns `object`, boxes value types and needs a cast back to `T`. - A `switch` on `typeof(T)` with one branch per supported type, which silently misses every type nobody listed. - A delegate parameter such as `Func<string, T>` that the caller must supply on every call. C# 11 static abstract interface members removed the need. **.NET 7** added `IParsable<TSelf>` in the `System` namespace, and the built-in types implement it. ## The interfaces | Interface | Static abstract members | Typical use | |---|---|---| | `IParsable<TSelf>` | `Parse(string, IFormatProvider?)`, `TryParse(string?, IFormatProvider?, out TSelf)` | parsing whole strings | | `ISpanParsable<TSelf> : IParsable<TSelf>` | `Parse(ReadOnlySpan<char>, IFormatProvider?)`, `TryParse(ReadOnlySpan<char>, IFormatProvider?, out TSelf)` | parsing a slice of a larger buffer | | `IUtf8SpanParsable<TSelf>` | the same pair over `ReadOnlySpan<byte>` of UTF-8 text | parsing bytes straight from a stream | Implementers in .NET 10 include every built-in numeric type, `string`, `bool`, `char`, `Guid`, `DateTime` and `TimeSpan`. `INumberBase<TSelf>` inherits `ISpanParsable<TSelf>`, so any method already constrained to `INumber<T>` can call `T.Parse` with no extra constraint. ## Writing ParseSamples<T> ```csharp static T[] ParseSamples<T>(string[] cells, IFormatProvider? provider) where T : IParsable<T> { var result = new T[cells.Length]; for (int i = 0; i < cells.Length; i++) result[i] = T.Parse(cells[i], provider); return result; } ``` What the call does with bad input depends on the type's own `Parse`, and for the numeric types it is: 1. `null` text throws `ArgumentNullException`. 2. Text in the wrong format, such as `"12x"` for `int`, throws `FormatException`. 3. A value that does not fit, such as `"300"` for `byte`, throws `OverflowException`. `T.TryParse` reports the same failures by returning `false`; the interface documents the `out` value as undefined on failure, so do not use it. A type that does not implement the interface never reaches run time. `Uri` has no `IParsable<Uri>`, so `ParseSamples<Uri>` fails with **CS0311**, "There is no implicit reference conversion from 'System.Uri' to 'System.IParsable<System.Uri>'." ## The culture trap The `IFormatProvider` argument is not optional ceremony. For the numeric types a `null` provider resolves to `NumberFormatInfo.CurrentInfo`, the **current culture**. `double.Parse` accepts thousands separators, and in de-DE the dot is the group separator, so on such a server: - `"3.5"` parses as **35** and `"4.25"` as **425**, with no exception. - The same call with `CultureInfo.InvariantCulture` returns 3.5 and 4.25. Generic code makes the trap easier to miss, because the call site no longer shows which type argument is culture-sensitive. The rule for a statistics library is simple: - Samples from files, CSV exports, configuration and protocols: pass `CultureInfo.InvariantCulture`. - Values a person typed into a UI: pass that person's culture explicitly. - Never rely on `null` unless "whatever this machine's culture is" really is the requirement. ## Choosing the constraint - `IParsable<T>` when the method parses whole strings. - `ISpanParsable<T>` when it slices a line or a rented buffer and wants `T.Parse(line.AsSpan(start, length), provider)` without allocating one substring per cell. - Nothing extra when `T` is already constrained to `INumber<T>`. - Your own types join by implementing the interface with **static** methods: an instance `Parse` fails with CS8928, "cannot implement the interface member because it is not static". ## Implementing IParsable on your own type A `Money` value read from the same files can flow through `ParseSamples<Money>` once it implements the interface: ```csharp readonly record struct Money(decimal Amount) : IParsable<Money> { public static Money Parse(string s, IFormatProvider? provider) => new(decimal.Parse(s, NumberStyles.Number, provider)); public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out Money result) { bool ok = decimal.TryParse(s, NumberStyles.Number, provider, out decimal amount); result = new Money(amount); return ok; } } ``` Two details are worth copying: the implementation passes the caller's `provider` straight through instead of choosing a culture itself, and it repeats the `[NotNullWhen(true)]` annotation from the interface so nullable analysis keeps working for callers. `ParseSamples<Money>(cells, CultureInfo.InvariantCulture)` then parses `"12.50"` into `Money(12.50m)`, and `Money.TryParse("abc", ...)` returns `false` without throwing. If `Money` should also parse slices, implement `ISpanParsable<Money>` instead; it inherits `IParsable<Money>`, so the string methods are still required and every caller constrained to either interface accepts it.

  • What do T.Parse and T.TryParse do with bad input in this generic code?
    They run the type argument's own parser. For the numeric types, `T.Parse` throws `ArgumentNullException` for null text, `FormatException` for text such as `"12x"`, and `OverflowException` for a value that does not fit, such as `"300"` into `byte`. `T.TryParse` returns `false` instead; the interface documents the `out` value as undefined on failure, so do not read it.
  • When would you constrain to ISpanParsable<T> instead of IParsable<T>?
    When the method slices a larger buffer, such as a CSV line or a rented `char[]`, and wants `T.Parse(line.AsSpan(start, length), provider)` without allocating a substring per cell. `ISpanParsable<T>` inherits `IParsable<T>`, so the string overloads stay available, and every `INumber<T>` already satisfies it through `INumberBase<T>`.
  • How does your own Money type become usable with ParseSamples<T>?
    Declare `Money : IParsable<Money>` and implement `public static Money Parse(string s, IFormatProvider? provider)` and the matching static `TryParse`. Both must be static: an instance `Parse` fails with CS8928. After that, `ParseSamples<Money>(cells, CultureInfo.InvariantCulture)` compiles and runs `Money`'s parser.

  • Passing null as the provider parses with the invariant culture.
  • Any type with a public static Parse method satisfies where T : IParsable<T>.
  • A type without IParsable<T> fails at run time with InvalidCastException.
  • Generic parsing still needs Convert.ChangeType and a cast back from object.
  • TryParse leaves a usable value in its out parameter when it returns false.
open as a page

In C#, what problem do static abstract interface members solve, and how does a generic Mean<T> where T : INumber<T> use them?

level: middleimportance: should knowfreq 48%

basics

~20 s

Before C# 11, an interface could require only instance members, so generic code could not use operators or static factories on T. Static abstract members (C# 11, .NET 7) let INumber<T> require them, so Mean<T> can write T.Zero, sum += v and T.CreateChecked(count).

open as a page

In C# generic math, what do byte.CreateChecked, CreateSaturating and CreateTruncating return for 300, and which should Mean<T> use to convert its count?

level: seniorimportance: should knowfreq 28%

basics

~20 s

byte.CreateChecked(300) throws OverflowException, CreateSaturating(300) returns 255 and CreateTruncating(300) returns 44, the low eight bits. Mean<T> should use T.CreateChecked(values.Length): a count that does not fit in T is a bug, not a value to clamp or wrap.

open as a page

In C#, how do you let your own Money struct flow through a generic Sum<T>, and why constrain T to IAdditionOperators<T, T, T> rather than INumber<T>?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Implement the narrow interfaces the method needs, Money : IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money>, with a static operator + and AdditiveIdentity. INumber<T> would force about sixty members, including Parse and Money * Money, that money does not have.

open as a page

As lead of a C# statistics package targeting netstandard2.0 and net8.0, would you replace its per-type Mean overloads with one INumber<T> generic method?

level: principalimportance: should knowfreq 22%

basics

~20 s

Not as a replacement. Keep the per-type overloads, which netstandard2.0 needs and compiled consumers bind to, and add a generic Mean on the net8.0 target only, with the narrowest constraints and an explicit result type, forwarding the old overloads to it.

open as a page

In a C# generic Add<T> where T : IAdditionOperators<T, T, T>, why does checked(a + b) throw for int.MaxValue but wrap for a struct defining only operator +?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

In a checked context the compiler calls the checked operator +, a static virtual member of IAdditionOperators. int implements it with overflow-checked addition and throws OverflowException; a struct that defines only operator + gets the default body, which calls that unchecked operator and wraps.

open as a page