//Takes a list of Employees and a Delegate. public static void PromoteEmployee(List <Employee> lstEmployees, EligibleToPromoteDelegate IsEmployeeEligible) { //Loops thru each employee object. foreach (Employee employee in lstEmployees) { //Passes employee to the delegate. //No hard coded logic on how to promote employee. if (IsEmployeeEligible(employee)) { Console.WriteLine("Employee {0} Promoted", employee.Name); } } }
public static void IsEligibleToPromote(List <Employee> employeeList, EligibleToPromoteDelegate eligibleToPromoteDelegate) { foreach (Employee emp in employeeList) { if (eligibleToPromoteDelegate(emp)) { Console.WriteLine("Promotable"); } else { Console.WriteLine("Not Promotable"); } } }
static void Main(string[] args) { //Get list of employees. List <Employee> lstEmployees = new List <Employee>(); lstEmployees = GetEmployeeList(); //Assign Promote() to delegate. EligibleToPromoteDelegate promoteMethod = new EligibleToPromoteDelegate(Program.Promote); //Promote employees. Employee.PromoteEmployee(lstEmployees, promoteMethod); Console.ReadKey(); }
static void Main(string[] args) { List <Employee> employeeList = new List <Employee>() { new Employee() { Id = 1, Name = "John", Experience = 5 }, new Employee() { Id = 2, Name = "Mark", Experience = 7 }, new Employee() { Id = 3, Name = "George", Experience = 2 }, new Employee() { Id = 4, Name = "Bill", Experience = 6 }, new Employee() { Id = 1, Name = "Cannor", Experience = 9 } }; // Here we are able to call different Bussiness logic without without Console.WriteLine("____________________________________Employee with exp > 5_____________________________________"); EligibleToPromoteDelegate eligibleToPromote = new EligibleToPromoteDelegate(Promote); //IsEligibleToPromote(employeeList, eligibleToPromote); Employee.IsEligibleToPromote(employeeList, eligibleToPromote); Console.WriteLine("____________________________________Employee with exp > 3_____________________________________"); EligibleToPromoteDelegate eligibleToPromote3 = new EligibleToPromoteDelegate(Promote3); Employee.IsEligibleToPromote(employeeList, eligibleToPromote3); //IsEligibleToPromote(employeeList, eligibleToPromote3); //The Function Pointer Delegate got replaced with Lambda expression Console.WriteLine("____________________________________Employee with exp > 5_____________________________________"); Employee.IsEligibleToPromote(employeeList, x => x.Experience > 5); Console.ReadKey(); }