A quick tutorial to learn delegates in C#
Learn delegates in C# with a detailed example !
Introduction
In this short tutorial, we will learn about delegates in C#. To follow this article, you only need to have a basic knowledge of C# and Visual Studio installed!
What are the delegates?
A delegate is a type that can contain a reference to a method. The reference can be modified at runtime. Delegates are used to pass a function as a parameter.
Declaration of delegates
Delegates are declared using the delegate keyword :
[modifier] delegate [returned_type] [delegate_name] ([parameter_list]);
modifier: This is the access modifier of the delegate, it can be private, public, protected or internal.
delegate: It is the keyword which is used to define the delegate.
returned_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
delegate_name: It is the user-defined name or identifier for the delegate.
parameter_list: This contains the parameters which are required by the method when called through the delegate.
Example :
Now, let's take a concrete example. First, in a namespace called DelegatesDemo for example, let's create the class Person :
internal class Person
{
// Name of the person
public string Name { get; set; }
// Age of the person
public int Age { get; set; }
}
This class has two properties, Name that indicates the name of the person, and the property Age which indicates the age of the person.
Then, in the Main function, let's Create a list of people called listOfPerson and add different people to it :
// Create a list of people
Person p1 = new Person() { Name = "Walter", Age = 33};
Person p2 = new Person() { Name = "Peter", Age = 14 };
Person p3 = new Person() { Name = "Gaspard", Age = 45 };
Person p4 = new Person() { Name = "Leland", Age = 65 };
Person p5 = new Person() { Name = "Dave", Age = 12 };
List<Person> listOfPerson = new List<Person>();
listOfPerson.Add(p1);
listOfPerson.Add(p2);
listOfPerson.Add(p3);
listOfPerson.Add(p5);
Now that we have a list containing different people, the idea is to create a function that displays different people based on specific criteria. We don't want to create multiple functions for this, we just need one function that takes a title, a list of people and a filter.
But before, let's create a delegate in the class program:
private delegate bool FilterMethod(Person p);
Now, let's create DisplayFiltered which takes the list of people in the parameters and the filter method (This is the criterion on which we will filter the list of people) :
/// <summary>
/// A method that displays the people with a filter given
/// </summary>
/// <param name="title"> The title of the filtration </param>
/// <param name="personList"> The list of people to filter </param>
/// <param name="Filter">The filter to be applied </param>
static void DisplayFiltered(string title, List<Person> personList, FilterMethod Filter)
{
Console.WriteLine($"Displaying {title} :");
foreach(var p in personList)
{
// Check if the person passes the filer
if (Filter(p))
{
Console.WriteLine($"{p.Name} {p.Age}");
}
}
}
Now, let's create our filter method :
/// <summary>
/// A filter for minor persons
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private static bool IsMinor(Person p)
{
return p.Age < 18;
}
/// <summary>
/// Check if the person's name contains the letter 'i'
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private static bool ContainsI(Person p)
{
return p.Name.Contains('i');
}
Now, in the main function, let's call the function DisplayFiltered with these two filters :
// Filter the people based on a specific criterion
DisplayFiltered("Kids", listOfPerson, IsMinor);
DisplayFiltered("Contains i", listOfPerson, ContainsI);