Events
- To communication between objects (notify other object, notification)
- To build Loosely Coupled Applications
- To help extend application
A publisher is an object that contains the definition of the event and the delegate. A publisher class object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.
e.g. Microsoft (publisher) organize an event and notify developers (subscriber) attend (handle) the event.
Points
- Use event keyword with delegate type to declare an event.
- Check event is null or not before raising an event.
- Subscribe to events using "+=" operator. Unsubscribe it using "-=" operator.
- Function that handles the event is called event handler. Event handler must have same signature as declared by event delegate.
- Events can have arguments which will be passed to handler function.
- Events can also be declared static, virtual, sealed and abstract.
- An Interface can include event as a member.
- Events will not be raised if there is no subscriber
- Event handlers are invoked synchronously if there are multiple subscribers
- The .NET framework uses an EventHandler delegate and an EventArgs base class.
Delegates
- Help you pass a function as paramater to handle Callback or event handler.
- It is pointer to a function.
- Agreement/Contract between Publisher and Subscriber
- Determines the signature of the event handler method in Subscriber
VideoEncoder will call MailService after video encoded. Normally we will
code inside videoEncoder, but in future MessageService come in, we need to change
VideoEncoder code, so we create an event, and let MessageService to point to
it.
VideoEncoder don’t know Mail Service and MessageService at all.
Delegate Anonymous Method
Methods without a name, just the body.
Delegate Anonymous Method
Methods without a name, just the body.
NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); };
//calling the delegate using the anonymous method nc(10);
No comments:
Post a Comment