Chapter 10. Delegates and Events


Delegates are the foundation of events. If you have used scripting languages before, you should be familiar with the concept of events. A user may interact with a Web page and click a button. The action of clicking generates an OnClick event. The JavaScript in the page may then do something as a result of the click action.

Delegates are classes that store functions. A developer first defines a delegate class. The definition of the delegate ”as you will see in the sections in this chapter ”contains a prototype for the type of functions that the delegate can store. A developer then declares a variable of the delegate type and assigns a function to it. The function could be an instance function in an object, or a static function. The only requirement is that the delegate can only store functions that match the prototype of functions used in declaring the delegate. A developer can then use the delegate variable to invoke the function that the delegate stores.

You may be tempted to think that that sounds too complicated, and that you will probably never use delegates. So how are delegates used practically? Delegates are normally used for the purpose of making callback calls. To understand callbacks consider a Modem class that has a method called Connect. Connect may do a few steps: open COM port, wait for ring tone, dial number, establish connection, etc. As a developer invoking the Connect method in the Modem class, you may want to get status information to display to the user. The question is, once you call the Connect method, how do you get notifications of the progress?

Delegates solve this problem. The Connect method could accept as a parameter a delegate to a function in the developer's caller class that offers information to the user. The Connect method then would periodically invoke the function in the developer's class as it is executing to provide progress information. This is called a callback mechanism. The callback function is the function in the originator code that the Modem class can call as it is executing.



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net