Sunday, April 5, 2015

Delegates Example

Delegates Example


class Program
    {
        static void Main(string[] args)
        {
            List<Employee> empList = new List<Employee>
            {
                new Employee{ Id = 1,Name= "Mary",Salary=5000,Experience = 5},
                new Employee{ Id = 2,Name= "Mike",Salary=4000,Experience = 4},
                new Employee{ Id = 3,Name= "John",Salary=6000,Experience = 6},
                new Employee{ Id = 4,Name= "Todd",Salary=3000,Experience = 3}
            };
            IsPromotable isPromotable = new IsPromotable(Promote);
            Employee.PromoteEmployee(empList,isPromotable);

            Employee.PromoteEmployee(empList, x=> x.Experience >= 5);  // using lambda expression
            Console.ReadKey();
        }

        public static bool Promote(Employee emp)
        {
            if (emp.Experience >= 5)
            {
                return true;
            }
            return false;
        }
    }

    public delegate bool IsPromotable(Employee emp);

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public static void PromoteEmployee(List<Employee> employeeList, IsPromotable isPromotable)
        {
            foreach (Employee emp in employeeList)
            {
                if (isPromotable(emp))
                {
                    Console.WriteLine(emp.Name + " promoted");
                }
            }
        }
    }

No comments:

Post a Comment