Func and Action C # reps used by companies?
In C #, Action
and Func
are extremely useful tools for reducing code duplication and communication. And reducing duplication and making code reusable is important for any company.
It's a shame that many developers shy away from them because they don't understand them.
Adding Action and Func to your toolbox is a very important step in improving your C # code.
As a great use case: Linq
based on Action
and Func
andPredicate
source to share
Here's an example of the power of these constructs, which illustrates for me the emptiness of the "junior developers who may not understand" argument.
If you have a class Organisation
that contains a collection of objects Department
, and if a class Department
contains a collection of objects Employee
, how do you get a complete set of employees for the organization
You can loop through objects and create a collection:
var allEmployees = new List<Employee>();
foreach (var department in organisation.Departments)
{
foreach (var employee in department.Employees)
{
allEmployees.Add(employee);
}
}
or you can just use the single operator
var allEmployees = organisation.Departments.SelectMany(d => d.Employees).ToArray();
This code is a term and less susceptible to human error than a manual loop, and immutability of the resulting array is less error prone than a modified list. To get these benefits, you need to be comfortable using lambda to represent constructs Func
and Action
.
source to share