C# – understand delegate

A delegate can be seen as a placeholder for a/some method(s).

By defining a delegate, you are saying to the user of your class, “Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called”.

Here is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateExample1
{

///

/// A class to define a person
///

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

class Program
{
//Our delegate
public delegate bool FilterDelegate(Person p);

static void Main(string[] args)
{

//Create 4 Person objects
Person p1 = new Person() { Name = "John", Age = 41 };
Person p2 = new Person() { Name = "Jane", Age = 69 };
Person p3 = new Person() { Name = "Jake", Age = 12 };
Person p4 = new Person() { Name = "Jessie", Age = 25 };

//Create a list of Person objects and fill it
List people = new List() { p1, p2, p3, p4 };

//Invoke DisplayPeople using appropriate delegate
DisplayPeople("Children:", people, IsChild);
DisplayPeople("Adults:", people, IsAdult);
DisplayPeople("Seniors:", people, IsSenior);

Console.Read();
}

///

/// A method to filter out the people you need
///

/// A list of people
/// A filter
/// A filtered list
static void DisplayPeople(string title, List people, FilterDelegate filter)
{
Console.WriteLine(title);

foreach (Person p in people)
{
if (filter(p))
{
Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
}
}

Console.Write("\n\n");
}

//==========FILTERS===================
static bool IsChild(Person p)
{
return p.Age = 18;
}

static bool IsSenior(Person p)
{
return p.Age >= 65;
}
}
}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply