In C#, both Func and Action are delegates used for handling methods, but they serve different purposes:
Func: Represents a method that returns a value. It can have up to 16 input parameters and a mandatory return type.
Action: Represents a method that does not return a value (i.e., void). It can have up to 16 input parameters but no return type.
Examples:
Using Func
Func add = (a, b) => a + b; Console.WriteLine(add(5, 3)); // Output: 8
Here, Func<int,int,int> takes two integers as input and returns an integer.
Func<T1, T2,....,TResult> myFunc = methodOrLambda;
//-----------------
Using Action
Action greet = name => Console.WriteLine($"Hello, {name}!"); greet("Jobin"); // Output: Hello, Jobin!
Here, Action takes a single string as input but returns nothing (void).
//------------------------------------------------------------------------------------------------------------------------------------------
Key Takeaways:
Use Func when you need a return value.
Use Action for operations that perform actions but do not need to return anything.
Both support lambda expressions and anonymous methods.
//----------------------------------------------------------------------------------------------------------------------------------------
Func as Callback ,example
SyntaxEditor Code Snippet
void Main()
{
List<int> data=[2,4,6,8];
ProcessData(data,GetSquare);
}
// You can define other methods, fields, classes and namespaces here
public static void ProcessData(List<int> data, Func<int, int> callback)
{
foreach (var item in data)
{
int result = callback(item); // Invoke the callback
Console.WriteLine($"Processed: {result}");
}
}
public static int GetSquare(int i)
{
return i * i;
}
//---------------------------------------------------------------------------------
result:
Processed: 4
Processed: 16
Processed: 36
Processed: 64
//-----------------------------------------------------------------------