csharp / intermediate
Snippet
Mapping Data with Func Delegates
Func<T, TResult> is a built-in delegate type that represents a function taking one argument and returning a value. It allows you to pass logic as a parameter to other methods, facilitating functional programming patterns in C#.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;using System.Collections.Generic;public class LambdaMapper {public static void Execute() {Func<int, int> square = x => x * x;List<int> numbers = new List<int> { 1, 2, 3, 4 };foreach (var num in numbers) {Console.WriteLine($"Square of {num}: {ApplyLogic(num, square)}");}}public static int ApplyLogic(int value, Func<int, int> logic) {return logic(value);}}
Breakdown
1
Func<int, int> square = x => x * x;
Defines a lambda expression that squares an integer using the Func delegate signature.
2
public static int ApplyLogic(int value, Func<int, int> logic)
A higher-order function that accepts a delegate as an argument.