- Func: represents a function
- Action: represents a method
namespace pav.actionExample;
class Program
{
static void AddMethod(int x, int y)
{
Console.WriteLine(x + y);
}
static void Main()
{
//declared action
Action<int, int> Add1 = AddMethod;
//inline action
Action<int, int> Add2 = (x, y) => { Console.WriteLine(x + y); };
Add1(2, 3);
Add2(2, 3);
}
}
Previously we reduced our code using funcs, now we can leverage both funcs and actions to further reduce, simplify and decouple our code.
namespace pav.funcActionExample;
class Program
{
struct Employee
{
public string FirstName;
public string LastName;
public Employee(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}
}
class EmployeeService
{
public List<Employee> Employees { get; } = new List<Employee>() {
new Employee("Pawel","Chooch"), new Employee("Steve","Smith"),
new Employee("Ian","Price"), new Employee("Tomek","Wan"),
new Employee("Jacques","Cocion") };
public void ProcessEmployee(Func<Employee, string> formatEmployeeFunc, Action<string> printAction)
{
if (formatEmployeeFunc is not null && printAction is not null)
foreach (Func<Employee, string> del in formatEmployeeFunc.GetInvocationList())
foreach (var e in Employees)
printAction(del(e));
}
}
static void Main()
{
var es = new EmployeeService();
Func<Employee, string> formatFunc = null;
formatFunc += e => $"{e.FirstName} {e.LastName}";
formatFunc += e => $"{e.FirstName.Substring(0, 1)}. {e.LastName}";
es.ProcessEmployee(formatFunc, (string str) => Console.WriteLine(str));
}
}