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.
//-----------------
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.