0 day streak
csharp / expert
Snippet

Generic Functional Pipeline Extensions

Expert C# developers often use extension methods to implement functional patterns. This 'Pipe' method enables linear composition of functions, transforming a nested call structure into a readable sequence, which improves maintainability and reduces variable clutter.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public static class FunctionalExtensions
{
// Maps an input to an output via a delegate
public static TOut Pipe<TIn, TOut>(this TIn input, Func<TIn, TOut> transform)
=> transform(input);
}
// Usage: Chain operations in a readable top-to-bottom flow
var result = "1234"
.Pipe(int.Parse)
.Pipe(n => n * 2)
.Pipe(n => $"Value: {n}");
Breakdown
1
this TIn input, Func<TIn, TOut> transform
Extends any type TIn with a method that accepts a transformation function returning TOut.
2
.Pipe(int.Parse)
Passes the string '1234' directly into the int.Parse method without intermediate variables.