What is Generic Delegates and its Types.
In C#, a generic delegate is a delegate that can work with any data type. This is achieved by using the Func or Action delegates along with generics.
Here's an example of a generic delegate using Func:
using System;
class Program
{
static void Main()
{
Func add = (a, b) => a + b;
Func concatenate = (a, b) => a + b;
Console.WriteLine(add(1, 2)); // Outputs: 3
Console.WriteLine(concatenate("Hello, ", "world!"));
}
}
In this example, Func int, int, int is a generic delegate that takes two int parameters and returns an int.
Similarly, Func string, string, string takes two string parameters and returns a string.
Action Delegates:
🔸Action delegates are used for methods that do not return a value (void methods). They can take up to 16 input parameters.
For example:
Action logMessage = (message) => Console.WriteLine(message);
logMessage("Hello, world!");
🔸 use Action when you need a delegate for a void method.
🔸use Func when you need a delegate for a method that returns a value.
Comments
Post a Comment