blogs

miércoles, 1 de julio de 2015

Delegates and EventHandler

What is a delegate?

A delegate is an object that knows how to call a  method
A delegate type defines the method signature.
A delegate is a type, that represent the reference to a method with a list particular of parameters and a return type. Can treat methods as an assigned  object to variables and pass them as parameters .
the main  application is in the creation and handled of events.




Declaration of a delegate and methods same signature



To an instance method and static methods:




Reduce syntax


Invoke to the instance of delegate
To invoke to method or subscribed methods to a new instance of delegate , we can call it using Invoke with the parameters  and we can save the result in a variable.
For example:




Reduce syntax

Run Unit Test









What is an event?
A event allows to notify when something happens
A method can register its interest to an event.
The methods registered  will be executed when the event happens.
Define an  event
An event is defined based on a delegate.




Initialize the event as an empty delegate to avoid having that validate if this is null every time that we launch the event.

Launch Event
This is invoke the event as we know do it with a delegate. The type event is  an EventHandler, this is a delegate that accepts void method and receive two parameters: an Object and EventArgs.



Handle and receive events 
We must create methods(EventHandlers) that comply with signature of the event and those must be registered with the event to be notified when happens the event.
Add the eventHandler as a event on list of execution





Define the eventHandler that it will execute in reaction to the event.




Run Test









No hay comentarios:

Publicar un comentario