Saturday, 7 May 2011

Delegates and Events in C#

Delegate
A delegate in  C# language allows us to reference a method. If we are using a C or C++ then we would sound familiar because a delegate because it 
is basically a function pointer. Delegates have other uses in addition to event handling. Delegate maintains three important pieces of information :  

    1. The name of the method on which it make calls.  

    2. Any argument (if any) of this method.  

    3. The return value (if any) of this method.

What is a Function Pointer?

Function Pointers are pointers, i.e. variables, which point to the address of a function.
Types of Delegate 
Delegates are of two types
          1.Single Cast delegate 

                public delegate <return type>  <delegate name>(parameters)

          2.Multi Cast delegate               
                public
delegate void <delegate name>(parameters)
Advantage of using Delegate
Dynamic binding can be done by using delegate because we can call more than one methods at a time dynamically by calling the delegate in which the methods is defined.
Example

namespace delgnew
 {
      public delegate int Delg(int x, int y);
       public class Math 
     {
       public static int Add(int x, int y)  
       { 
         return x + y;    
       }    
         public static int Multiply(int x, int y)
       {     
        return x * y;    
        }
     }
   class Fun  
     {     
             static void Main(string[] args) 
      {     
      Delg del1 = new Delg(Math.Add);    
      int add1 = del1(7, 7);
      Console.WriteLine("7 + 7 = {0}\n", add1);
      Delg del2 = new Delg(Math.Multiply);            
      int multiply1 = del2(7,7); 
      Console.WriteLine("7 * 7 = {0}", multiply1);                                          
      Console.ReadLine();
      }
    }
}

Static Delegates
Denoting static field is meaning that it will not be modified. You can invoke delegates without declaring a local delegate instance. Just pass in the static delegate of the class.
 
Delegates as Properties
The problem with static delegates is that they must be instantiated  whether or not they are ever used.
Event
 An event might be a button push, a menu selection in short we can cay that  something happens and you must respond to it. You cannot predict the order in which events will arise.
For example
- when you click a button, it might raise the Click event. When you add to a drop-down list, it might raise a List Changed event.
Defining Event

using System;
class Eventtest
{
    public event EventHandler myfun
    {
        add
        {
            Console.WriteLine ("Event Fired");
        }
      remove
        {
            Console.WriteLine ("Controlled");
        }
    }       
      static void Main()
    {
        Eventest et = new Eventtest();
        et.myfun += new EventHandler (et.DoNothing);
        et.myfun -= null;
    }   
    void DoNothing (object sender, EventArgs e)
    {
    }
}
    An event allows a class (or other object) to send notifications to other classes (or objects) that something has occurred. In simple terms an event is the outcome of a specific action. If you have developed programmers in graphical user interfaces (GUI) then you are very familiar with Event handling.
When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application.
 

1 comment:

  1. good post.thanks u

    regards,
    bhaskar
    http://csharpektroncmssql.blogspot.com

    ReplyDelete