Using delegates in C#

Ever been stumped by the question “What is a delegate?” and “How would you use them in your code?”. Here is an excellent explanation from Stack Overflow.

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that’s when you’ll need delegates.

The code below implements a simple console application to demonstrate this use of delegates. Notice how we pass the functions IsChild, IsAdult & IsSenior as parameters to the function DisplayPeople as the delegate type FilterDelegate.

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

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

        static void Main(string[] args)
        {
            // create 4 person objects
            var p1 = new Person() { Name = "Alan", Age = 26 };
            var p2 = new Person() { Name = "Jamie", Age = 69 };
            var p3 = new Person() { Name = "Dariaus", Age = 12 };
            var p4 = new Person() { Name = "Graham", Age = 41 };

            // create a list of person objects and fill it
            var people = new List<Person>() { p1, p2, p3, p4 };
            DisplayPeople("Childern:", people, IsChild); 
            DisplayPeople("Adults:", people, IsAdult);
            DisplayPeople("Seniors:", people, IsSenior);

            Console.Read();
        }

        static void DisplayPeople(string title, List<Person> people, FilterDelegate filter)
        {
            Console.WriteLine(title);

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

            Console.Write("nn");
        }

        // These functions match the FilterDelegate delegate (They return bool and take a single parameter 'p' which is a person)
        // This means they can be passed as parameters into functions as a FilterDelegate
        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;
        }
    }
}

I think this is a really nice and easy example of how to use delegates in C#.

Original source: when-why-to-use-delegates

Advertisements

Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s