Saturday, 16 November 2024

Dynamically passing method : Action, Func delegates

 In C#, you can dynamically pass a method or a delegate to another method by using either delegates or Action/Func types. These approaches allow you to abstract the invocation of methods in a flexible and reusable way.

Let’s look at how to pass methods dynamically using Action (for methods that return void) or Func<T> (for methods that return a value). Both Action and Func are predefined generic delegates in .NET.

Using Action Delegate

  static void Main(string[] args)
  {
    ExecuteAction(printMessage); //Passing method via Action delegate

// Passing an anonymous method (lambda) via Action delegate
    ExecuteAction(() => Console.WriteLine("Hello from Lamda expression"));
  }

// Method that accepts an Action delegate
  static void ExecuteAction(Action action)
  {
      action();
  }
 
// A method that matches the Action delegate signature (void method)
  static void printMessage()
  {
      Console.WriteLine("Hello world");
  }
OUTPUT
  //Hello world
  //Hello from Lamda expression

Using Func<T>Delegate

  static void Main(string[] args)
  {
    int result = ExecuteFunc(getSum, 4, 5);
    int result2 = ExecuteFunc((a, b) => a + b, 5, 6);
    Console.WriteLine(result);
    Console.WriteLine("Result from Lamda: "+result2);
  }

  static int ExecuteFunc(Func<int, int, int> func, int n1, int n2)
  {
      return func(n1, n2);
  }

  static int getSum(int a, int b)
  {
      return a + b;
  }

OUTPUT
  //9
  //Result from Lamda: 11

Key Points:

  • Action<T>: Used for methods that return void.
  • Func<T, TResult>: Used for methods that return a value.
  • You can pass both named methods and lambda expressions (anonymous methods) as delegates.
  • Delegates are type-safe, meaning that they require the method signature to match.

This flexibility lets you dynamically pass any method or lambda expression to another method in C#.


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives