Delegates are the ultimate function pointer. Developers familiar with C and C++ are very familiar with function pointers and their lack of instance-based knowledge. A delegate can be thought of as a call back mechanism, essentially saying, “Please invoke this method for me when the time is right.”
Consider the following scenario: Your department has just hired a new employee. Human Resources needs to be notified when a new employee is hired so they can put them to sleep with endless paper work and boring drivel about company policies and practices. This type of interaction is a perfect example of a delegate. Basically, Human Resources is requesting a notification when a new employee is hired and provides a method to be invoked. Listing 2.1.32 shows the basic use of delegates.
Listing 2.1.32 implements the HR scenario and makes use of a delegate to notify HR when a new person has been hired. The delegate OnNewHire is defined on line 14. Notice the use of the delegate keyword to denote what is being declared. Remember that C# does not allow for global methods, so C# would issue an error without the delegate keyword.
The HR class provides a handler for the delegate. The method name does not have to be the same as the name of the delegate; this was done to make it easier to follow. The Department class provides a method AddOnNewHireDelegate to handle the “hooking-up” of the delegate with the intended handler. Notice the call on line 53 that actually adds the HR handler to the Department. A delegate is a type in C# and requires an instance, hence the use of the new keyword to create a new delegate.
I would encourage any developer to explore delegates in detail because their use in .NET is prolific, especially in Windows Forms development.
3.149.254.48