Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:20
Show Gist options
  • Save dnasca/bee0ee9e92a520ea3e17 to your computer and use it in GitHub Desktop.
Save dnasca/bee0ee9e92a520ea3e17 to your computer and use it in GitHub Desktop.
fun with delegates
using System;
using System.Collections.Generic;
//the goal for this Employee class is NO HARD CODED LOGIC, we can accomplish this using delegates
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int CurrentSalary { get; set; }
public int YearsExperience { get; set; }
//create 2 parameter method
public static void PromoteEmployee(List<Employee> employeeList, IsPromotable isEligibleToPromote) //delegate passed into function as a parameter
{
foreach (Employee employee in employeeList)
{
if (isEligibleToPromote(employee)) //use the logic that the delegate points to (Promote function)
{
Console.WriteLine("{0} is eligible for a promotion", employee.Name);
}
}
}
}
public delegate bool IsPromotable(Employee empl); //
public class Program
{
public static void Main()
{
//instantiate a list of object of type Employee, call it empList
List<Employee> empList = new List<Employee>();
//add some objects to the list
empList.Add(new Employee() { ID = 12376, Name = "Bob", CurrentSalary = 54000, YearsExperience = 6 });
empList.Add(new Employee() { ID = 12376, Name = "George", CurrentSalary = 28000, YearsExperience = 3 });
empList.Add(new Employee() { ID = 12376, Name = "Harold", CurrentSalary = 71000, YearsExperience = 11 });
empList.Add(new Employee() { ID = 12376, Name = "AnnoyingGuy", CurrentSalary = 4200, YearsExperience = 1 });
empList.Add(new Employee() { ID = 12376, Name = "Chris", CurrentSalary = 32000, YearsExperience = 2 });
//pass the method 'Promote' as a parameter to the IsPromotable delegate constructor
IsPromotable isPromotable = new IsPromotable(Promote); //instantiate a new delegate object, isPromotable will point to method 'Promote'
//invoke the PromoteEmployee method
Employee.PromoteEmployee(empList, isPromotable); //IsPromotable points directly to the method 'Promote'
Console.ReadKey();
}
//pass this method to the constructor of the delegate
public static bool Promote(Employee emp)
{
if (emp.YearsExperience >= 5)
{
return true;
}
else
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment