Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Developers,

Can any one clear my doubt, What is the difference between calling the function directly and
calling(invoking) the function through delegate,

what are the advantages of using delegate to call function ?

Thanks in advance.
Posted

The advantage is that you don't have to know the name of the event at compile time - you can call any method which matches the signature at run time.

For example, if you write a method to print an invoice which uses a Write delegate, then to can supply the method with a Write method to print to a TextBox, another to print to a file, a third to the Console, a fourth to the printer, and so on, without changing the original method at all - it doesn't have to know where the data is going, it just relies on you doing something relevant with the data in every method you supply to the delegate. This means that the method can be nice and clean, without any changes needed to add to the list of outputs.

There are loads of other uses, but they all stem from this basic premise.
 
Share this answer
 
Like function pointers, you may change the delegate at runtime, see the documentation[^].
 
Share this answer
 
The advantage of using delegates:

1. It provides a way to encapsulate your methods.

2. It solves the problem of very tight coupling between your business logic code and User Interface UI. Means whenever you changes to your business logic code(add/Edit/delete any method) you have to change the UI code as well accordingly. But by using delegates your UI code will point to an abstract pointer and that will access that business logic code. Hence the UI need not to know about the business logic code.

hope it helps :)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900