C# Delegates Part 3


This entry is part 3 of 8 in the series C# Delegates

This post is a continuation from the previous post. You need to have a look at the previous post to understand what we are doing here in this part because the code listings in this part depend on the code listings in the previous part. In this post we continue on with the Photos program. We are going to show how a consumer of this code can create their own filter. They want to code a RemoveRedEye filter.

Adding a Delegate

Now we want to add a delegate. PhotoFilterHandler is the name of the delegate we will be adding. To do this we will be using the delegate keyword.

namespace Photos
{
    class PhotoProcessor
    {
        // PhotoFilterHandler is our delegate
        public delegate void PhotoFilterHandler(Photo photo);

        public void Process(string path, PhotoFilterHandler filterHandler)
        {
            var photo = Photo.Load(path);
            filterHandler(photo);
            photo.Save();
        }
    }
}

The client of this code is our Program.cs. In the code, where does filterHandler come from? It is just a name we created.

namespace Photos
{
    class Program
    {
        static void Main(string[] args)
        {
            var myVar = new PhotoProcessor();
            var filters = new PhotoFilters();
            PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyContrast;
            myVar.Process("pic.jpg", filterHandler);

            // below we add another pointer
            filterHandler += filters.ApplyBrightness;

            Console.ReadKey();
        }
    }
}

Our framework is extensible because the user can add their own RemoveRedEyeFilter.

namespace Photos
{
    class Program
    {
        static void Main(string[] args)
        {
            var myVar = new PhotoProcessor();
            var filters = new PhotoFilters();
            PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyContrast;
            // below we add another pointer
            filterHandler += filters.ApplyBrightness;
            filterHandler += RemoveRedEyeFilter;

            myVar.Process("pic.jpg", filterHandler);
        }
        static void RemoveRedEyeFilter (Photo photo)
        {
            Console.WriteLine("Remove Red Eye was added here by the consumer!");
        }
    }
}

What we have is a multicast delegate.

Series Navigation<< C# Delegates Part 2C# Delegates Part 4 >>