Table of Contents

Class ActionStrategy<TIn>

Namespace
PatternKit.Behavioral.Strategy
Assembly
PatternKit.Core.dll

Represents a "first-match-wins" strategy pipeline built from predicate/action pairs, where actions perform side effects and do not return a value.

public sealed class ActionStrategy<TIn>

Type Parameters

TIn

The input type accepted by each predicate and action.

Inheritance
ActionStrategy<TIn>
Inherited Members
Extension Methods

Examples

var log = new List<string>();

void Log(string msg) => log.Add(msg);

var s = ActionStrategy<int>.Create()
    .When(static i => i > 0).Then(static i => Log($"+{i}"))
    .When(static i => i < 0).Then(static i => Log($"-{i}"))
    .Default(static _ => Log("zero"))
    .Build();

s.Execute(5);   // logs "+5"
s.Execute(-3);  // logs "-3"
s.Execute(0);   // logs "zero"

Remarks

ActionStrategy<TIn> is the action-only counterpart to Strategy<TIn, TOut> and TryStrategy<TIn, TOut>. It uses ActionStrategy<TIn>.Predicate delegates to decide whether an ActionStrategy<TIn>.ActionHandler applies. The first predicate that returns true determines which action is executed.

If no predicates match:

Thread-safety: The built strategy is immutable and thread-safe. The ActionStrategy<TIn>.Builder is not thread-safe.

Methods

Create()

Creates a new ActionStrategy<TIn>.Builder for constructing an ActionStrategy<TIn>.

public static ActionStrategy<TIn>.Builder Create()

Returns

ActionStrategy<TIn>.Builder

A new ActionStrategy<TIn>.Builder instance.

Examples

var s = ActionStrategy<string>.Create()
    .When(static s => string.IsNullOrEmpty(s)).Then(static _ => Console.WriteLine("empty"))
    .Default(static _ => Console.WriteLine("other"))
    .Build();

s.Execute("");  // prints "empty"
s.TryExecute("x"); // prints "other", returns true

Execute(in TIn)

Executes the first matching action for the given input.

public void Execute(in TIn input)

Parameters

input TIn

The input value.

Remarks

Iterates predicates in registration order; runs the corresponding action for the first match and returns. If no predicate matches and a default was configured via Default(ActionHandler), the default action runs. Otherwise, throws via NoStrategyMatched().

Exceptions

InvalidOperationException

Thrown when no predicates match and no default action is configured.

TryExecute(in TIn)

Attempts to execute the first matching action for the given input.

public bool TryExecute(in TIn input)

Parameters

input TIn

The input value.

Returns

bool

true if an action (or default) executed; otherwise false.

Remarks

Unlike Execute(in TIn), this method never throws due to no matches.