What is delegates?
- A delegate is an object that knows how to call a method or a group of method, or has a reference to functions.
- A delegate type definds the kind of method that delegate instance can call which are return type and parameter types list.
delegate int Transformer(int x);
static int Square(int x) => x * x;
Transformer t = Square;
int ans = t(3); //9
Why do we need delegates?
- For designing extensibility and flexibility
- In some cases, we have altenative option which is interface.
var filters = new PhotoFilters();
From the example above, we can see that everytime we want to create a new filter, we have to add code, create that filter, then recompile and redeploy the whole class again. We can use delegate to prevent this.
public class PhotoProcessor
public delegate void PhotoFilterHandler(Photo photo);
public void Process(string path, PhotoFilterHandler filterHandler)
In Main class:
var processor = new PhotoProcessor();
var filter = new PhotoFilters;
filterHandler = filters.ApplyBrightness;
filterHandler += filters.ApplyContrast;
filterHandler += RemoveRedEye;
Special delegates: Action and Func
When to use delegate over interface?
- Use a delegate when an eventing design pattern in use
- The caller doesn’t need to access other properties or methods on the object implementing the method.