csharp / intermediate
Snippet
Logic Injection with Func and Action Delegates
Using delegates like Func and Action allows you to pass logic as arguments, making your methods flexible and reusable without hardcoding behavior.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
public void ProcessData(int[] data, Func<int, int> transformer, Action<int> logger){foreach (var item in data){int result = transformer(item);logger(result);}}// Usage:// ProcessData(new[] {1, 2}, x => x * 10, res => Console.WriteLine(res));
Breakdown
1
Func<int, int> transformer
A delegate that takes an int and returns an int.
2
Action<int> logger
A delegate that takes an int and returns void (useful for side effects).
3
transformer(item)
Executes the injected logic on the current item.