CKTIS / C#
Delegates in `Match` and culture-invariant formatting
Pass separate success and error delegates to `Match` with a shared return type. Use `FormattableString.Invariant` to format interpolation without relying on the current culture.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
public delegate TResult Func<in T, out TResult>(T arg);
// Delegate parameters of the example's Match<T, TResult>:
Func<T, TResult> onSuccess, Func<string, TResult> onError
// Static method signature on System.FormattableString:
public static string Invariant(FormattableString formattable);System.Func<T,TResult> is a delegate type that takes one argument of type T and returns TResult. Func<string,TResult> is that same generic type with T fixed to string, not a separate API type or an overload. A compatible method or lambda can supply either delegate. For delegate variance conversions, in T is contravariant and out TResult is covariant: Func<object,string> can be assigned to Func<string,object>. Variance applies to reference types, not value types.
In this C# 12 and .NET 8 example, Match is a user-defined helper. It accepts a Func<T,TResult> for success and a Func<string,TResult> for failure. The ?: operator invokes only the selected delegate, passes it either the value or the error text, and returns its TResult. The error text is data, not an exception; if the selected delegate throws, the helper does not catch it.
Targeting System.FormattableString directly with $"..." retains the composite format and the already evaluated arguments, so formatting is deferred, not expression evaluation. The static method FormattableString.Invariant returns a string using CultureInfo.InvariantCulture without changing the current culture; it throws ArgumentNullException for null. Ordinary interpolation to string uses the current culture by default. You cannot pass a finished string to Invariant to recover its arguments. Invariant formatting does not replace serialization or escaping.
Examples
using System;
Func<decimal, string> formatAmount = amount =>
{
FormattableString message = $"amount={amount:F2}";
return FormattableString.Invariant(message);
};
Func<string, string> formatError = error => $"error={error}";
Console.WriteLine(Match(true, 12.5m, "missing", formatAmount, formatError));
Console.WriteLine(Match(false, 0m, "missing", formatAmount, formatError));
static TResult Match<T, TResult>(bool succeeded, T value, string error,
Func<T, TResult> onSuccess, Func<string, TResult> onError)
=> succeeded ? onSuccess(value) : onError(error);Result
amount=12.50 error=missing
The first call runs `formatAmount`: `F2` gives two decimal places, and the invariant culture gives the decimal point in `amount=12.50`. The second call runs only `formatError` and prints `error=missing`.
Related lessons
- C# · Lesson 41 · Advanced · Version: 3