Understanding Callbacks with Func and Action Delegates

 

How to use Func and Action delegates for implementing callbacks with practical examples. Let's break this down into steps and then provide some code implementations.

Callbacks with Func and Action Delegates

Func and Action delegates are powerful features in C# that allow us to pass methods as parameters to other methods. This concept is known as "callbacks" because one method (the callback) is called by another method.

Key points to consider

  • Func delegate represents a method that returns a value
  • Action delegate represents a method that doesn't return a value
  • These delegates allow for flexible and reusable code structures

Example Implementation

Let's create a simple example that demonstrates both Func and Action delegates:

internal class Program
{
    private static void Main(string[] args)
    {
        //Example 1: Using Func delegate
        int result = Calculate(5, AddFive);
        Console.WriteLine($"Result: {result}");   // OutPut : Result:10

        //Example 2 : Using Action delegate
        ProccessNumbers(new int[] { 1,2,3},PrintNumber);

        Console.WriteLine("Done");
    }


    private static int AddFive(int num)
    {
        return num + 5;
    }


    private static void PrintNumber(int num)
    {
        Console.WriteLine($"Proccessing Number: {num}");
    }


    private static int Calculate(int value, Func<int, int> callback)
    {
        return callback(value);
    }


    private static void ProccessNumbers(int[] numbers, Action<int> callback)
    {
        foreach (var number in numbers)
        {
            callback(number);
        }
    }


}

 

Author
Jio
124 906 28