Higher-order functions (HOF) are functions that can take a function as an argument or return a function or both. In C#, higher-order functions are achieved using delegates, lambda expressions and expression trees.
Example 1: Using a Delegate
// Declare a delegate that takes an int and returns an int
public delegate int IntOperation(int x);
public class Program
{
// Higher-order function that takes a delegate as an argument
public static int PerformOperation(int value, IntOperation operation)
{
return operation(value);
}
public static void Main()
{
// Create a delegate instance that points to the Square method
IntOperation square = x => x \* x;
// Pass the delegate to the higher-order function
int result = PerformOperation(5, square);
Console.WriteLine(result); // Output: 25
}
}
Example 2 : Using lambda expression
// Higher-order function that takes a lambda expression as an argument
public static int PerformOperation(int value, Func<int, int\> operation)
{
return operation(value);
}
// main method
// Define a lambda expression that squares a number
Func<int, int> square = x => x * x;
// Pass the lambda expression to the higher-order function
int result = PerformOperation(5, square);
Example 3: Function as a Return Value
public class Program
{
// Higher-order function that returns a function
public static Func<int, int\> GetOperation(bool isSquare)
{
if (isSquare)
{
return x => x \* x;
}
else
{
return x => x + x;
}
}
public static void Main()
{
// Get a function that squares a number
Func<int, int> operation = GetOperation(true);
// Use the returned function
int result = operation(5);
Console.WriteLine(result); // Output: 25
}
}
In c#, higher order functions are everywhere. If one have used LINQ, must have used HO functions. Collection’s Where() is the good example.
[Read More]