Monday, March 4, 2013

Delegates & Events

C# training online Delegates and Events

Delegates and Events

Delegates and Events are two very powerful features of .NET. Events: cornerstone of GUI programming 
Delegates:
       implement  events.
       class that encapsulates a method signature.
       equivalent to function pointers.
       "unlike function pointers, delegates are object oriented and type-safe.”
       serves as the basis for the event-handling model in C# but can be used in a context removed from event handling.
       allows to pass references of entry points to methods and invoke them without making an explicit method call.
       defines the signature of the method it can call.
Events and delegates- Difference
Events are the actions of the system on user manipulations (e.g. mouse clicks, key press, timer etc.) or any event triggered by the program.
Delegate is type which holds the method(s) reference in an object.
Event is a C# Modifier.
Delegate is a C# type.


Types of delegates

Delegate is a class and is inherited from base delegate class of .NET class library when it is declared which can be from either System.Delegate or System.MulticastDelegate.
Two types of delegates: Singlecast and Multiplecast delegates
1. Singlecast delegate:
       point to single method at a time.
       delegate is assigned to a single method at a time.
       derived from System.Delegate class.
2. Multicast Delegate:
       a delegate is wrapped with more than one method.
       In C#, delegates are multicast; they can point to more than one function at a time.
       derived from System.MulticastDelegate class.
Defining and using delegates
There are three steps in defining  and using delegates:
  1. Declaration
  2. Instantiation
  3. Invocation
1. Declaration
        keyword ‘delegate ’
[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);
       attributes factor : normal C# attribute.
       modifier : new, public, private, protected, or internal.
       ReturnType: data types; can also be a type void or name of class.
       Name: valid C# name.
       Parentheses is required . If this method will not take any argument, leave the parentheses empty.

Example:
 public delegate void DelegateExample(); //delegate with return type                   
                                                                          //void and accept no 
                                                                         //parameters.
2. Instantiation

DelegateExample d1 = new DelegateExample(Display);


3. Invocation

d1();

Working of delegates
Documentation details about how delegates work:
  1. A delegate declaration defines a class that is derived from the class System.Delegate.
  2. A delegate instance encapsulates an invocation list, which is a list of one or more methods, each of which is referred to as a callable entity.
  3. For instance methods, a callable entity consists of an instance and a method on that instance.
  4. For static methods, a callable entity consists of just a method.
  5. Invoking a delegate instance with an appropriate set of arguments causes each of the delegate instance's callable entities to be invoked with the given set of arguments.
Benefits of delegates
  1. Delegates are object oriented and type-safe and secure as they ensure that the signature of the method being called is correct.
  2. Delegate helps in code optimization.
Usage areas of delegates 
  1. The most common example of using delegates is in events.
  2. They are extensively used in threading
  3. Delegates are also used for generic class libraries, which have generic functionality, defined.
An Anonymous Delegate
       No need to explicitly define a method prior to using the delegate.
       if a delegate itself contains its method definition it is known as anonymous method.
       Sample program and output is shown below:








Point to remember about Delegates:


  1. are similar to C++ function pointers, but are type safe.
  2. gives a name to a method signature.
  3. allow methods to be passed as parameters.
  4. can be used to define callback methods.
  5. can be chained together; for e.g. multiple methods can be called on a single event.
  6. C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
  7. helps in code optimization.
Events
       event: message sent by an object to signal occurrence of an action.
       Action: user interaction/ triggered by some other program logic.
       Event sender: The object that raises the event.
       Event receiver: The object that captures the event and responds.

Prerequisites for raising an event:

  1. A class that provides event data.
  2. An event delegate.
  3. The class that raises the event.
By convention in the .NET Framework, when an event is raised, it passes event data to its event handlers. The event data is provided by the System.EventArgs class or by a class that is derived from it.
Declaring Events
       directly tied to a delegate.
       A delegate object encapsulates a method so that it can be called anonymously.
       An event is a mechanism by which a client class can pass delegates to methods that need to be invoked whenever something happens.
       When it does, the delegate(s) given to it by its clients are invoked.

Syntax to declare an event in C# :
public delegate void testDelegate(int a);
public event testDelegate MyEvent;
       Once an event is declared, it must be associated with one or more event handlers before it can be raised.
        An event handler is a method that is called using a delegate.
        += operator is used to associate an event with an instance of a delegate that already exists.
For example:
Myform.MyEvent += new testEvent(MyMethod);
An event handler may also be detached as follows:
MyForm.MyEvent -= new testEvent(MyMethod);
How does the event keyword work ?
Whenever an event is defined for a class, the compiler generates three methods that are used to manage the underlying delegate i.e.:
  1. add_<EventName>:
       public method that calls the static Combine method of System.Delegate to add another method to its internal invocation list.
       This method is however not used explicitly.
       The same effect is achieved by using the += operator as specified before.
2. remove_<EventName>:
              public method that calls the static Remove method of System.Delegate to 
         remove a receiver from the event’s invocation list.
              This method is also not called directly.
               -= operator.
3. raise_<EventName>:
               A protected method that calls the compiler generated Invoke method of the delegate, to call each method in the invocation list.
Delegates and Events in Windows Forms
       Default delegates are provided for the events of the controls and classes of the .NET Framework base class library.
       When using Windows Forms to create rich client applications, events can be handled in two ways:
  1. By declaring a method that has a signature that is the same as the corresponding event handler delegate and then registering the method as a handler (using +=).
  2. By overriding the corresponding event method, when your class is a subclass of the Control class.

0 comments:

Post a Comment