Delegates
So what is a delegate ? and Why does it come into existence ?
A delegate is an object which knows how to call a method(or a group of methods). Simpler way to define is, delegate is a reference or a pointer to a function .
Now why do we need like that ? We can call methods directly , why do we need a delegate that is calling methods for us . Well this technique is helpful for us in designing extensible and flexible applications.
If we are asked to create a framework for image processing , So it looks some thing like this
So ,if I release this framework,the client or developer who is consuming the framework can use this as below and it might look as below
Now if one of the developer wanted to apply another filter to resize the image , you need to create that filter and re-compile and re-deploy both ImageFilter and ImageProcessor classes. Now imagine every time a developer in the world want a new filter you need to re-compile and and re-deploy the code which is not a good idea. So with delegate we can make this framework extensible such that a developer can create their own filters without relying on you .
How do we use a delegate to make it extensible ?
First we need to define a delegate type :
public delegate void ImageFilter(Image image);
Here , void is the signature of the delegate .
To make it extensible , I need to use delegate in the ImageProcessor class . The delegate is defined as such
| ImageProcessor with delegate changes |
Now , after such change in the framework code , my client looks something like this and as mentioned earlier as we can extend it to create a new filter but need to make sure that the signature of the method and delegate matches .
So , here we can see the developer has defined a new filter with out changing anything in the framework. Now you have a understanding of what delegate is and how you can use them .
Here we have created a custom delegate that points to a method that returns void and takes a parameter of type Image .Instead of creating our custom delegate , we could use one the existing delegate in .NET framework .In .NET we have two delegates Action and Func that are generic . The difference between them is Action is pointed to a method that returns a void and Func is pointed to a method that returns a value.In this case as our methods are pointed to a method which is returning void , we can use Action as below
| Image Processor with the Action delegate |
So , finally though this we have covered what a delegate is and why is it used and how the custom delegates are used and how it can be replaced with a .NET framework provided delegates .
Inspired and Reference : Microsoft blogs and Mosh Hamendi videos .
Source Code Available at : GitHub
Comments
Post a Comment