
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
158
|
Chapter 3: Classes and Structures
The highlighted code has been modified from the original code.
Discussion
Using an interface mechanism for callbacks is a simple but effective alternative to
using delegates. The interface mechanism is only slightly faster than using a delegate
since you are simply making a call through an interface.
This interface mechanism requires a notification client (
NotifyClient) that imple-
ments a callback interface (
INotificationCallbacks) to be created. This notification
client is then passed to an object that is required to call back to this client. This
object is then able to store a reference to the notification client and use it appropri-
ately whenever its callback methods are used.
When using the callback methods on the
notificationObj, you should test to deter-
mine whether the
notificationObj is null; if so, you should not use it or else a
NullReferenceException will be thrown:
t.ProcessSomething( );
Console.WriteLine( );
t.UnAttachCallback( );
t.ProcessSomething( );
}
public void MultiCallBackThroughIFace( )
{
INotificationCallbacks notificationObj = new NotifyClient( );
MultiTask t = new MultiTask(notificationObj);
t.ProcessSomething( );
Console.WriteLine( );
INotificationCallbacks notificationObj2 = new NotifyClientType2( );
t.AttachToCallback(notificationObj2); ...