Table of Contents

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

T

The 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:

  1. Fast path: direct cast when input is already T.
  2. Strategy chain execution: first matching handler transforms input to T.
  3. Default: returns default when no handler matches.

The default pipeline includes handlers for:

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

v object

The input value.

Returns

TType

The coerced value when successful; otherwise default.

Type Parameters

TType

The target type to coerce into.

See Also

From(object?)

Attempts to coerce v to T.

public static T? From(object? v)

Parameters

v object

The input value to coerce. May be null.

Returns

T

The coerced value when successful; otherwise default.

Remarks

Order of operations:

  1. If v is null, returns default.
  2. If v is already T, returns it unmodified.
  3. Executes the strategy chain and returns the first successful result.