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"));
}
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 returnvoid
.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