Class TryStrategy<TIn, TOut>
- Namespace
- PatternKit.Behavioral.Strategy
- Assembly
- PatternKit.Core.dll
Represents a chain of TryStrategy<TIn, TOut>.TryHandler delegates that are executed in order until one succeeds (returns true).
public sealed class TryStrategy<TIn, TOut>
Type Parameters
TInThe input type accepted by each handler.
TOutThe output type produced by a successful handler.
- Inheritance
-
TryStrategy<TIn, TOut>
- Inherited Members
- Extension Methods
Remarks
TryStrategy<TIn, TOut> is designed for allocation-free, hot-path usage where you want a first-match-wins execution model without exceptions.
The strategy is immutable once built. Typical construction is via the TryStrategy<TIn, TOut>.Builder fluent DSL:
var strategy = TryStrategy<object, string>.Create()
.Always(FirstHandler)
.Or.When(() => condition).Add(ConditionalHandler)
.Finally(FallbackHandler)
.Build();
if (strategy.Execute(input, out var result))
Console.WriteLine($"Matched: {result}");
else
Console.WriteLine("No handler matched.");
Methods
Create()
Creates a new TryStrategy<TIn, TOut>.Builder for constructing a TryStrategy<TIn, TOut>.
public static TryStrategy<TIn, TOut>.Builder Create()
Returns
- TryStrategy<TIn, TOut>.Builder
A new TryStrategy<TIn, TOut>.Builder instance.
Examples
var strategy = TryStrategy<string, int>.Create()
.Always((in string s, out int r) => int.TryParse(s, out r))
.Finally((in string _, out int r) => { r = 0; return true; })
.Build();
Execute(in TIn, out TOut?)
Executes the strategy by invoking each handler in order until one succeeds.
public bool Execute(in TIn input, out TOut? result)
Parameters
inputTInThe input value passed to each handler.
resultTOutThe first successfully produced result. Undefined when the method returns false.
Returns
Remarks
Stops execution as soon as a handler returns true. Remaining handlers are not evaluated.