Delegates Make Confusion (Where to use) In C#

Definition

Delegates is a callback function, that means it is an interface partner between two parties.

Proof: Need proof, how callback is working? Okay, let us see one simple example.

Requirement

I have a CMaths class, its job is calculating sum of number, same time this function inform to the calling parties, progress of sum status.

Problem

How function inform to calling parties, If I return the value function terminates without completing the sum calculation, hey if am using thread, so  problem will solve? Partially, but you have to do more work, what is the best procedure to implement?

Solution: Callback

Interact with calling parties, I need communication partners, that is called delegates & delegates need to know to whom my contract partner, that partner is method name (callback in C#, function pointer in c++) and partner must speak same language (same signature).

Implementation

Step 1: Inform only status (text information), so my Delegate speaking language is string.

Delegates Syntax

Access-type delegate return type delegate name (type of arguments)

Example:

Delegates Syntax

The following is simple maths class, calculating the sum of numbers

maths class

Find Sum method calculating sum of numbers function arguments:

  1. Total sum: Max numbers
  2. Delegates parameter

Solution

Each for loop iterations, callback function invokes (delegatePartner). Who asked the status?

Diagram

Diagram

In main program

Create an object for CMaths class and inform maths class WatchMathsSteps function is a partner function (callback function) for you

main program

Each iteration FindSum function fire status to the WatchMathsSteps function & this function print the status to the console.

Result is:

run

Conclusion

This is just an example proof How Delegates are working.


Similar Articles