CKTIS / C#
Tuple-returning Func delegates, accumulators, and size validation
Use one delegate to report conversion success and another to update an accumulator. Throw an exception when the requested size is outside the allowed range.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
System.Func<TSource, (bool Success, TResult Value)> convert;
System.Func<TAcc, T, TAcc> accumulate;
if (size < 0 || size > source.Count)
throw new System.ArgumentOutOfRangeException(nameof(size), size, "Size must be between zero and the source count.");Func<TSource,(bool,TResult)> is a delegate from System. It takes one TSource argument and returns one value: a System.ValueTuple<bool,TResult> value type, not two out parameters. Field names such as Success and Value are optional; you can deconstruct the result with var (success, value). The flag's meaning is part of the callback contract: here false means to ignore the value, while true makes it usable even if it equals the type's default value.
Func<TAcc,T,TAcc> is a different delegate type from System. It takes the current accumulator of type TAcc and an item of type T, then returns the next accumulator of type TAcc. The last type argument to Func is the return type. In FoldPrefix, T is the conversion result type (TResult in the first notation). The method starts from seed, visits the first size items in order, and updates the accumulator only after a successful conversion. Rejected items still count toward size.
FoldPrefix is an example method, not a .NET API. The valid size is 0 through source.Count, inclusive. Zero returns seed without invoking either delegate. If size < 0 || size > source.Count, the method throws System.ArgumentOutOfRangeException before indexing any item or invoking either delegate. The three-argument constructor takes the parameter name (nameof(size)), the invalid value (size), and a message describing the range, in that order. Read the name and value through ParamName and ActualValue.
Examples
using System;
using System.Collections.Generic;
using System.Globalization;
string[] items = { "2", "bad", "3", "100" };
Func<string, (bool Success, int Value)> convert = text =>
{
bool success = int.TryParse(text, NumberStyles.Integer,
CultureInfo.InvariantCulture, out int value);
return (success, value);
};
Func<int, int, int> accumulate = (sum, value) => sum + value;
Console.WriteLine(FormattableString.Invariant($"size 3: {FoldPrefix(items, 3, 10, convert, accumulate)}"));
Console.WriteLine(FormattableString.Invariant($"size 0: {FoldPrefix(items, 0, 10, convert, accumulate)}"));
try
{
FoldPrefix(items, 5, 10, convert, accumulate);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(FormattableString.Invariant($"out of range: {ex.ParamName}={ex.ActualValue}"));
}
static TAcc FoldPrefix<TSource, T, TAcc>(
IReadOnlyList<TSource> source, int size, TAcc seed,
Func<TSource, (bool Success, T Value)> convert,
Func<TAcc, T, TAcc> accumulate)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(convert);
ArgumentNullException.ThrowIfNull(accumulate);
if (size < 0 || size > source.Count)
throw new ArgumentOutOfRangeException(nameof(size), size,
"Size must be between zero and the source count.");
TAcc acc = seed;
for (int i = 0; i < size; i++)
{
var (success, value) = convert(source[i]);
if (success)
acc = accumulate(acc, value);
}
return acc;
}Result
size 3: 15 size 0: 10 out of range: size=5
Console example for C# 12 and .NET 8: size 3 yields 15 (10 + 2 + 3) because `bad` is skipped and `100` lies outside the prefix. Size 0 yields 10. Size 5 is invalid for four items; the program prints the parameter name and value, not the exception message.
Related lessons
- C# · Lesson 29 · Advanced · Version: 3