Skip to content

Pattern Matching

WhenType<T> — "run this block if the target is of type T". A chainable companion to Conditional Invoke that reads naturally when you want a sequence of type checks.

Usage

csharp
using Servus.Functional;

object value = GetSomething();

value.WhenType<string>(s  => Console.WriteLine($"string: {s}"));
value.WhenType<int>   (i  => Console.WriteLine($"int:    {i}"));
value.WhenType<Order> (o  => Process(o));

Comparison with InvokeIf

Both check "is this object of type T?" and run a handler if so. Pick based on readability:

Use WhenType<T> forUse InvokeIf<T> for
IntentA value's concrete typeAn interface/capability the target might support
Handler returnsvoid onlyvoid or a value
Null handlingTarget can be null, handler doesn't runTarget can be null, handler doesn't run

API

csharp
public static class TypeExtensions
{
    public static void WhenType<T>(this object target, Action<T> handler);
}

Servus and happy coding! 🥨🍺