While taking a interview, training a fresher, or doing a code review for a fellow colleague. I often find people not using delegates and most of the time their understanding seems to be delegates are only used for Events!!! No where else.
So, here's something that might interest you.
Situation: There is a company which sends goodies monthly to its customers. If the copany board decides that they would send pens to children, coffee mugs to adults and walking stick to senior citizens.
Also, there is chance that adult age might change to 15 instead of 18 in future.
So, heres the code:
So, here's something that might interest you.
Situation: There is a company which sends goodies monthly to its customers. If the copany board decides that they would send pens to children, coffee mugs to adults and walking stick to senior citizens.
Also, there is chance that adult age might change to 15 instead of 18 in future.
So, heres the code:
class Program {
//Our delegate
public delegate bool FilterDelegate(Person p);
static void Main(string[] args) {
//Create 4 Person objects
Person p1 = new Person() { Name = "Amit", Age = 41 };
Person p2 = new Person() { Name = "Anit", Age = 69 };
Person p3 = new Person() { Name = "Asit", Age = 12 };
Person p4 = new Person() { Name = "Arit", Age = 25 };
//Create a list of Person objects and fill it
List<Person> people = new List<Person>() { //Somecode to get customer info };
GiveGiftstoPeople( people, IsChild); GiveGiftstoPeople( people, IsAdult); GiveGiftstoPeople( people, IsSenior);
Console.Read();
}
static bool IsChild(Person p) {
return p.Age <= 18;
}
static bool IsAdult(Person p) {
return p.Age >= 18;
}
static bool IsSenior(Person p) {
return p.Age >= 65;
}
static void GiftPens(List<Person> people, FilterDelegate filter) { foreach (Person p in people) { if (filter(p)) { Console.WriteLine("Pen Given To", p.Name, p.Age); } } Console.Write("\n\n"); }static void GiftCoffeeMugs(List<Person> people, FilterDelegate filter) { foreach (Person p in people) { if (filter(p)) { Console.WriteLine("Pen Given To", p.Name, p.Age); } } Console.Write("\n\n"); }static void GiftCoffeeMugs(List<Person> people, FilterDelegate filter) { foreach (Person p in people) { if (filter(p)) { Console.WriteLine("Mugs Given To", p.Name, p.Age); } } Console.Write("\n\n"); }static void GiftWalkingSticks(List<Person> people, FilterDelegate filter) { foreach (Person p in people) { if (filter(p)) { Console.WriteLine("Mugs Given To", p.Name, p.Age); } } Console.Write("\n\n"); }
No comments:
Post a Comment