Class Coercer<T>
- Namespace
- PatternKit.Examples.Strategies.Coercion
- Assembly
- PatternKit.Examples.dll
Provides strategy-driven, allocation-light coercion from object to T.
public static class Coercer<T>
Type Parameters
TThe target type to coerce values into. Common cases are primitives, nullable primitives, string, and string[].
- Inheritance
-
Coercer<T>
- Inherited Members
Examples
var i = Coercer<int>.From(JsonDocument.Parse("123").RootElement); // 123
var b = Coercer<bool>.From(JsonDocument.Parse("true").RootElement); // true
var s = Coercer<string>.From(JsonDocument.Parse("\"hello\"").RootElement); // "hello"
var arr = Coercer<string[]>.From(JsonDocument.Parse("[\"a\",\"b\"]").RootElement); // ["a","b"]
var n = Coercer<int?>.From("27"); // 27 via convertible fallback
Remarks
Coercer<T> compiles a typed pipeline of TryStrategy<TIn, TOut>.TryHandler delegates
exactly once per closed generic type (Coercer<int>, Coercer<string>, etc.).
At runtime, From(object?) performs:
- Fast path: direct cast when input is already
T. - Strategy chain execution: first matching handler transforms input to
T. - Default: returns default when no handler matches.
The default pipeline includes handlers for:
- JsonElement → string via ToString().
- JsonElement array → string[] (by enumerating elements).
- JsonElement number → int, float, double.
- JsonElement boolean → bool.
- Convertible fallback: if input is IConvertible and the target underlying type is primitive or decimal, uses ChangeType(object, Type, IFormatProvider) with InvariantCulture.
Thread safety: The compiled pipeline is immutable and static per closed generic type; From(object?) is thread-safe.
Performance: No LINQ; handlers are traversed as a flat array. The first matching handler wins.
Methods
Coerce<TType>(object?)
Convenience entry point that forwards to From(object?).
public static TType? Coerce<TType>(object? v)
Parameters
vobjectThe input value.
Returns
- TType
The coerced value when successful; otherwise default.
Type Parameters
TTypeThe target type to coerce into.
- See Also
From(object?)
Attempts to coerce v to T.
public static T? From(object? v)
Parameters
Returns
- T
The coerced value when successful; otherwise default.