0 day streak
csharp / intermediate
Snippet

Flexible Logic with Func Delegates

Func delegates allow you to pass behavior as a parameter, enabling highly flexible and reusable methods without hardcoding logic.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
public class Calculator
{
public int Execute(int a, int b, Func<int, int, int> operation)
{
return operation(a, b);
}
}
// Usage
var calc = new Calculator();
int sum = calc.Execute(10, 5, (x, y) => x + y);
int product = calc.Execute(10, 5, (x, y) => x * y);
Breakdown
1
Func<int, int, int> operation
Defines a delegate that takes two integers as input and returns one integer.
2
return operation(a, b);
Invokes the passed function logic with the provided arguments.