DEV Community

Rohit Cdy
Rohit Cdy

Posted on • Edited on

Delegate in C#

Delegate Example and Usages

What is a Delegate?

  • A delegate in C# is a type that represents references to methods with a specific parameter list and return type.

  • When you create an instance of a delegate, you can associate it with any method that has a compatible signature (matching parameters and return type).

  • Delegates allow you to pass methods as arguments to other methods.

Code Example

using System;
using System.Collections.Generic;

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

    // Define a delegate to represent filtering methods
    public delegate bool FilterDelegate(Person p);

    public static void Main()
    {
        // Create some Person objects
        Person p1 = new Person() { Name = "Rohit", Age = 26 };
        Person p2 = new Person() { Name = "Lal", Age = 40 };
        Person p3 = new Person() { Name = "Prashant", Age = 65 };

        // Populate a list with Person objects
        List<Person> people = new List<Person>() { p1, p2, p3 };

        // Display people based on different filters
        DisplayPeople("Children", people, IsChild);
        DisplayPeople("Adults", people, IsAdult);
        DisplayPeople("Seniors", people, IsSenior);

        Console.Read();
    }

    // Display people based on a specified filter
    static void DisplayPeople(string title, List<Person> 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.WriteLine();
    }

    // Filter methods
    static bool IsChild(Person p) => p.Age < 18;
    static bool IsAdult(Person p) => p.Age >= 18 && p.Age < 65;
    static bool IsSenior(Person p) => p.Age >= 65;
}

Enter fullscreen mode Exit fullscreen mode

Key Concepts Explained

Delegate Declaration:

  • We define a FilterDelegate to represent filtering methods that take a Person object and return a boolean value.
  • This delegate allows us to dynamically choose different filters for our list of people.

Method Definitions:

  • We have three filter methods: IsChild, IsAdult, and IsSenior.
  • These methods determine whether a person falls into the child, adult, or senior category based on their age.

Displaying People:

  • The DisplayPeople method takes a title, a list of people, and a filter delegate.
  • It iterates through the list and displays relevant information based on the specified filter.

Output:

Children:
Rohit, 26 years old

Adults:
Rohit, 26 years old
Lal, 40 years old

Seniors:
Prashant, 65 years old
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay