Multicast Delegate
Satya Prakash Chhikara
.NET 8 | .NET Core | ASP.NET | MVC | Software Development | Mobile Development | Web Development | ERP | CMS | Microsoft Technologies | AI Automation | DevOps | AWS | Azure
Multicast Delegate
Multicast Delegate is a delegate which holds references of more than a function pointer having same number of parameters and return types.
We can attach multiple references of method to a single delegate using += sign and those methods will be executed in same sequence as defined.
For example, let’s consider below example
We can attach multiple method to same delegate as below
?
?
Here you can see it called all methods in same sequence as those were referred to delegate object.
?
Many developers know this concept already but got confused where to use these delegates into code/project. It is very important, once you learn a concept, you must also know how to use this and where to use this. Think, of a solider who trained to aim to target, but until and unless he/she doesn’t know to whom he/she needs to shoot someone OR identify the situation when to use his/her aiming skills, it completely useless.
In same way, we also should have clear visibility how to use delegate in real project to make an impact.
So, lets explain where to use in detail. Most of developers are already aware of e-commerce website and you must have seen that delivery charges are free if payment exceed to some amount, but we don’t want to hard code that on front end application rather than we want to implement this inside order class. Also, we have multiple delivery partner to deliver order based upon Address Type.
?In above example, you can see, we haven’t written any logic to calculate delivery fee and choose delivery partner, rather than we declare delegates to process that data.
领英推荐
To achieve this and take out business logic outside Order class, Lets add new class “OrderProcessing” which implement 2 methods.
?
?
?
Now, let’s create few orders to test this
?
?
And we can write some logic to notify delivery partner and add more logic around this.
Also, delegate is used to define which function/method will be add if we add dynamic button to a page OR form.
?
?
?
?
?
?