public static void IsPromotable(List <Employee> emp, IsEligibleforPromotion IsEligible) // Pass the delegate as parameter which references the logic method which finds eligible/not { if (emp != null) { foreach (Employee employee in emp) { // if (emp.YearsOfExp > 5) // Hard coded logic inside a class , if at all anytime consumer (who uses this class) needs a logic change will be under trouble. if (IsEligible(employee)) // calling the method delegate { Console.WriteLine("Eligible"); } else { Console.WriteLine("Not Eligible"); } } } else { Console.WriteLine("Employee List is Empty"); } }
static void Main(string[] args) { Sample s = new Sample(); //Instantiating the delegates Addnumbers Add = new Addnumbers(s.Addnum); //constructor clearly shows the signature of the target method to be given, if there are any discrepancy , it will throw compile error // shows its type safety SayHello Say = new SayHello(s.SayHello); // if i try to give Addnum method here (int method), immediately shows error. //IsEligibleforPromotion IsEligible = emp => emp.Salary >= 10000; // Delegate instantiation IsEligibleforPromotion IsEligible = new IsEligibleforPromotion(Program.IsEligibleforPromote); // Delegate instantiation List <Employee> emplist = new List <Employee>(); // To understand the delegate usage, how to make resuable code logic emplist.Add(new Employee { Name = "Mike", Salary = 1000, YearsOfExp = 4 }); emplist.Add(new Employee { Name = "Mary", Salary = 11000, YearsOfExp = 5 }); emplist.Add(new Employee { Name = "Matt", Salary = 10000, YearsOfExp = 6 }); emplist.Add(new Employee { Name = "John", Salary = 8000, YearsOfExp = 5 }); //Calling the methods via Delegates Console.WriteLine(Add.Invoke(10, 150)); // Even this way/below way we can call the methods via Delegates. Console.WriteLine(Add(10, 250)); Console.WriteLine(Say("Gowthaman")); Employee.IsPromotable(emplist, IsEligible); // Calling the Method of consumed class which is out of our control Console.ReadLine(); }