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?
answer
- a static method turned into a requirement
- T.Parse and T.TryParse
- the IFormatProvider argument
- null means the current culture
- a span overload for slices
basics
~10 sIParsable<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 linesusing 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
Recall that IParsable<T> gives generic code T.Parse and T.TryParse, and that int, double, decimal, Guid and DateTime all implement it.
Explain the two static abstract members, why the provider argument matters, and how ISpanParsable<T> parses a slice without allocating substrings.
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.
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.