In some of the previous posts on delegates we defined a custom delegate. Instead of creating a custom delegate we could use one of the delegates that come with .NET framework. We have Action<> and Func<>.
Action<>
Instead of creating a custom delegate we could one of the existing delegates that come with .NET framework. We have two delegates that are generic: Action<> and Func<>.. Func<> points to a method that returns a value, whereas Action<> points to one that does not.
namespace Photos
{
class PhotoProcessor
{
// Remove our delegate and use Action<Photo> instead
//public delegate void PhotoFilterHandler(Photo photo);
public void Process(string path, Action<Photo> filterHandler)
{
var photo = Photo.Load(path);
filterHandler(photo);
photo.Save();
}
}
}
class Program
{
static void Main(string[] args)
{
var myVar = new PhotoProcessor();
var filters = new PhotoFilters();
//PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyContrast;
Action<Photo> filterHandler = filters.ApplyContrast; // remove above line
// 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!");
}
}
Alternative: Interfaces
For flexibility, an alternative is interfaces. How do we decide which one to use?