Chapter 6: Events and Delegates


Overview

Event-based programming is a cornerstone of the .NET Framework – it is fundamental to all .NET user-interface code, including Windows Forms and ASP.NET pages. Events can also be used effectively anywhere in applications to decouple the functionality of an object from other objects that depend on it. By exposing and firing events from within an object, we enable other objects to respond to its activities in ways that we did not necessarily anticipate when we coded the class. Therefore, events can be a powerful component in the interface of any C# type we code.

The event mechanism in the .NET Framework makes use of delegates (or callbacks). We introduced delegates briefly in Chapter 1 when we reviewed the .NET Framework Common Type System. A delegate encapsulates the signature of a function or subroutine. In C/C++, this would be similar to a function pointer. A function pointer is simply a memory address; the compiler has no knowledge of the signature of the method it points to. Therefore, function pointers are not type safe (you could pass a wrong type without the compiler noticing) and cannot be a part of a managed application. We define delegates to represent the signature of methods that we want to ‘call back’ in our application. We can then create an instance of a delegate and bind it to a particular method. We can use this delegate to invoke our chosen method. Because delegates can only point to a method of one specific signature, delegates can be type-safe.

In this chapter, we'll investigate the delegate mechanism in some detail. We'll see how delegates are compiled into MSIL code, which will help you understand how delegates work internally. Then we'll look at some advanced delegate issues, such as multi-cast delegates and asynchronous delegates.

Once we've seen how to use delegates, we'll examine the .NET Framework event model. Most programmers will be familiar with some sort of event model, but in the .NET Framework, events work differently from how they work in Visual Basic or Java. We'll describe how the event model makes use of delegates, and see how to use events in user-interface code. We'll also see how to use events as a general way of decoupling an event source object (which generates events) from event receiver objects (which receive event notifications).




C# Class Design Handbook(c) Coding Effective Classes
C# Class Design Handbook: Coding Effective Classes
ISBN: 1590592573
EAN: 2147483647
Year: N/A
Pages: 90

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