In C# generic math, what do byte.CreateChecked, CreateSaturating and CreateTruncating return for 300, and which should Mean<T> use to convert its count?
answer
- three answers to out of range
- throw, clamp or keep low bits
- 300 is 0x12C
- floating sources drop the fraction
- a count that silently shrinks
basics
~20 sbyte.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.
solid answer
~40 s`INumberBase<T>` declares three static virtual conversions, `CreateChecked<TOther>`, `CreateSaturating<TOther>` and `CreateTruncating<TOther>`, with `TOther : INumberBase<TOther>`; they differ only when the value does not fit. For 300 into `byte`, checked throws `OverflowException`, saturating clamps to 255, and truncating keeps the low eight bits of 0x12C, giving 44. From a floating-point source all three drop the fraction (`int.CreateChecked(2.9)` is 2), and an out-of-range `double` saturates even with `CreateTruncating`; converting into `float`, `double` or `Half`, an out-of-range value becomes infinity rather than throwing. `Mean<T>` converts its element count with `T.CreateChecked(values.Length)`, so with `T = byte` and 300 samples it throws instead of dividing by 44. The sum is a separate hazard: `byte`'s `+` wraps, so the real fix is a wider accumulator type parameter.
code
csharp · 10 linesusing System.Numerics;
Console.WriteLine(byte.CreateSaturating(300)); // 255
Console.WriteLine(byte.CreateTruncating(300)); // 44: low 8 bits of 0x12C
Console.WriteLine(byte.CreateSaturating(-1)); // 0
Console.WriteLine(byte.CreateTruncating(-1)); // 255
Console.WriteLine(int.CreateChecked(2.9)); // 2: the fraction is dropped
Console.WriteLine(int.CreateTruncating(3e10)); // 2147483647: from double it saturates
try { byte.CreateChecked(300); }
catch (OverflowException) { Console.WriteLine("OverflowException"); }go deeper
Recall that generic code converts numbers with T.CreateChecked, T.CreateSaturating and T.CreateTruncating instead of a cast.
Explain the three outcomes for a value that does not fit: throw, clamp to the range, or keep the low bits, with byte and 300 as the example.
Show the floating-point edges, why the count needs CreateChecked, and why the sum still overflows unless you accumulate in a wider type.
Set the rule for a numeric library: which conversions must be exact, where clamping is a documented behaviour, and how accumulator types appear in the public API.
## Why generic code needs conversion methods Inside a method constrained to `INumber<T>`, the cast `(T)values.Length` does not compile: the compiler reports **CS0030**, "Cannot convert type 'int' to 'T'", because built-in numeric conversions are not something a type parameter can promise. Generic math replaces the cast with three static members of `INumberBase<TSelf>`: - `static virtual TSelf CreateChecked<TOther>(TOther value)` - `static virtual TSelf CreateSaturating<TOther>(TOther value)` - `static virtual TSelf CreateTruncating<TOther>(TOther value)` Each requires `TOther : INumberBase<TOther>`. The default implementations ask `TSelf` and then `TOther` whether either knows the conversion, and throw `NotSupportedException` when neither does. For values that fit, all three return the same result; they differ only on the edges. ## The three answers to "it does not fit" Results printed by the .NET 10 SDK: | Call | `CreateChecked` | `CreateSaturating` | `CreateTruncating` | |---|---|---|---| | `byte` from `300` | `OverflowException` | 255 | 44 | | `byte` from `-1` | `OverflowException` | 0 | 255 | | `int` from `3e10` (`double`) | `OverflowException` | 2147483647 | 2147483647 | | `int` from `2.9` (`double`) | 2 | 2 | 2 | | `float` from `1e300` (`double`) | infinity | infinity | infinity | Reading the table: 1. **Checked** throws `OverflowException` when the value is outside the target's range. It behaves like a cast in a `checked` context. 2. **Saturating** clamps to `MinValue` or `MaxValue`. There is no cast syntax for this. 3. **Truncating**, between integer types, keeps the low-order bits: 300 is 0x12C, and the low byte 0x2C is 44. That matches an unchecked integer cast. ## Floating-point edges Floating-point sources and targets follow their own rules, which the table already hints at: - A fractional part is dropped toward zero by all three methods: `int.CreateChecked(2.9)` is 2 and `int.CreateTruncating(-2.9)` is -2. Losing the fraction is not overflow, so `CreateChecked` does not throw for it. - An out-of-range `double` converted to an integer **saturates even with `CreateTruncating`**, because a `double` has no low-order integer bits to keep. - `NaN` converted to `int` gives 0 through `CreateSaturating` and `CreateTruncating`, and `OverflowException` through `CreateChecked`. - Converting into `float`, `double` or `Half`, an out-of-range value becomes infinity, even with `CreateChecked`. `Half.CreateTruncating(100000)` is positive infinity, because `Half` tops out at 65504. ## Picking one in Mean<T> ```csharp static T Mean<T>(ReadOnlySpan<T> values) where T : INumber<T> { T sum = T.Zero; foreach (T v in values) sum += v; return sum / T.CreateChecked(values.Length); } ``` The count must be exact, so `CreateChecked` is right: `Mean<byte>` over 300 samples throws `OverflowException` instead of dividing by 44 (truncating) or by 255 (saturating). That fixes only the divisor. The **sum** is computed by `byte`'s own `+`, which wraps outside a `checked` context: `Mean<byte>` of 200 and 100 adds to 44 and returns 22. Two common repairs: - Accumulate in a second type parameter, `TAcc : INumber<TAcc>`, converting each element with `TAcc.CreateChecked(v)`; `MeanIn<byte, int>` of 200 and 100 returns 150. The BCL takes the same approach internally: `Enumerable.Sum(IEnumerable<float>)` accumulates in `double` through a private generic helper. - Write `sum = checked(sum + v)`, so overflow throws instead of wrapping. ## Converting between two type parameters The source does not have to be a concrete type. In `TResult Average<T, TResult>(T first, T second) where T : INumber<T> where TResult : INumber<TResult>`, the expression `TResult.CreateChecked((first + second) / T.CreateChecked(2))` converts a `T` into a `TResult` without either type being known when the method is written. That is the pattern behind result and accumulator type parameters: - the caller picks `T = int, TResult = double` and gets a fractional mean; - the same body serves `T = byte, TResult = int` for a sum that must not wrap; - an unsupported pair, such as a custom numeric type that neither side knows how to convert, throws `NotSupportedException` from the default implementation rather than failing at compile time, so it deserves a test. ## When the other two are right - `CreateSaturating` when clamping is the domain rule: a computed brightness, an audio sample or a progress value that must land in `byte` range. - `CreateTruncating` when you want the bit pattern, such as hashing or packing the low bits of a wider integer. Whichever you choose, the name now documents the intent at the call site, which a bare cast never did: a reviewer reading `T.CreateSaturating(level)` knows clamping was deliberate, and one reading `T.CreateChecked(count)` knows an overflow would be a bug.
- Why does Mean<byte> of 200 and 100 return 22 even though it uses CreateChecked?`CreateChecked` guards only the count. The sum is computed with `byte`'s own `+`, which wraps outside a checked context: 200 + 100 becomes 44, and 44 / 2 is 22. Accumulate in a wider type parameter with `TAcc.CreateChecked(v)`, or write `sum = checked(sum + v)` so the overflow throws.
- What does CreateTruncating do when converting a double into int?It drops the fraction toward zero, so -2.9 becomes -2, and an out-of-range value saturates to `int.MinValue` or `int.MaxValue`, because a `double` has no low-order integer bits to keep. `NaN` becomes 0. Bit truncation applies only between integer types.
- When is CreateSaturating the right choice?When clamping is the intended rule rather than a hidden bug: converting a computed colour channel, an audio sample or a percentage into `byte`, where 300 should become 255 and -5 should become 0. Use it deliberately and name it; it should never stand in for a missing range check on input.
Pouring into a cup that is too small: CreateChecked refuses and raises an alarm, CreateSaturating fills the cup to the brim and stops, and CreateTruncating behaves like an odometer that rolls past its last digit and keeps only the low digits.
- byte.CreateTruncating(300) returns 255.
- int.CreateChecked(2.9) rounds to 3.
- Converting 1e300 into float with CreateChecked throws OverflowException.
- A plain (T)count cast works inside a method constrained to INumber<T>.
- Using CreateChecked on the count also protects the sum from overflow.