CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Wednesday, August 30, 2006

Delegate and Multicast Delegate

Delegate is type which  holds the method(s) reference in an object.

it is also reffered as a type safe function pointers.

 

Delegates are types used to invoke one or more methods where the actual method invoked is determined at run time.

 

Advantages:

.Encapsulating the method's call from caller

.Effective use of Delegate improves the performance of application.

.used to call a method asynchronously.

 

Declaration:

public delegate type_of_delegate delegate_name()

Example : public delegate int mydelegate(int delvar1,int delvar2)

 

Note:

.you can use delegeate without parameter or with parameter list

.you should follow the same syntax as in the method

(if you are reffering the method with two int parameters and int return type

the delegate which you are declaring should be the same format.This is how it

is reffered as type safe function pointer)

 

Sample Program using Delegate :

 

public delegate double Delegate_Prod(int a,int b);

 

           class Class1

          {

                   static double fn_Prodvalues(intval1,int val2)

                   {

                           returnval1*val2;

                   }

                   static voidMain(string[] args)

                   {

                           

 

                             //Creating the DelegateInstance

                             Delegate_Prod delObj = newDelegate_Prod(fn_Prodvalues);

 

 

                             Console.Write("PleaseEnter Values");

 

                             int v1 =Int32.Parse(Console.ReadLine());

                             int v2 =Int32.Parse(Console.ReadLine());

 

                             //use a delegate forprocessing

 

                             double res =delObj(v1,v2);

                             Console.WriteLine ("Result:"+res);

                            Console.ReadLine();

 

                   }

          }

 

 

Explanation:

 

Here I have used a small programwhich demonstrates the use of delegate.

 

The delegate "Delegate_Prod" isdeclared with double return type and which

accepts only two integerparameters.

 

Inside the Class the method namedfn_Prodvalues is defined with double return

type and two integerparameters.(The delegate and method is having the same signature and parameterstype)

 

Inside the Main method the delegateinstance is created and the function name is passed to the delegate instance asfollowing.

 

Delegate_Prod delObj = newDelegate_Prod(fn_Prodvalues);

 

After this we are accepting the twovalues from the user and passing those values to the delegate

as we do using method.

 

delObj(v1,v2);

 

Here delegate object encapsulatesthe method functionalities and return the result as we specified

in the method.

 

MulticastDelegate

 

What is Multicast Delegate?

 

          It is a Delegate which holds the reference of more than one method.

Multicast delegates must contain only methods that return void; else there is a run-time exception.

 

 Simple Program using MulticastDelegate

 

delegate voidDelegate_Multicast(int x, int y);

 

Class Class2

{

   static void Method1(int x, inty)

   {

      Console.WriteLine("You r in Method 1");

   }

   static void Method2(int x, inty)

   {

      Console.WriteLine("You r in Method 2");

    }

   public static voidMain()

   {

      Delegate_Multicast func = new Delegate_Multicast(Method1);

     func += new Delegate_Multicast(Method2);

     func(1,2);             // Method1 and Method2are called

      func -= new Delegate_Multicast(Method1);

      func(2,3);             // Only Method2 iscalled

    }

 }                                

 

Explanation:

 

In the above example you can seethat two methods are defined named method1 and method2 which takes two integerparameters and return type as void.

In the main method the Delegateobject is created using the following statement

 

 Delegate_Multicast func = newDelegate_Multicast(Method1);

Then the Delegate is added usingthe += operator and removed using -= operator.

 

 

Using Delegates to handle Events

This article will focus on one aspect of delegates: how they are used to implement event handling. It is important to understand that while delegates are a general-purpose mechanism for calling methods indirectly, their principal uses in .NET are for

a) implementing events and

b) implementing call-back methods.

 

To get a sense of how delegates are used to implement events, we'll look at the implementation of a custom event.

 

Implementing a Custom Event

Events are notifications, or messages, from one part of an application to another that something interesting has happened. When an event is raised, all the delegates in the invocation list are executed in the order they were added. The sender of the event does not know which part of the application will handle the event, or even if it will be handled. It just sends the notification and is finished with its responsibilities. It is often necessary to provide some information about the event when the notification is sent. This is normally included in the EventArgs argument to the event handler. You will probably want to develop a class derived from EventArgs to send information for your custom events.

 

 

Writing a Custom Event -- Step-by-Step

Suppose you want to write a custom event called MyEvent for your custom control named MyControl that extends System.Windows.Forms.UserControl. Here are the steps you need to take.

 

1. Declare a delegate with the public access modifier. Here I will call this delegate MyEventHandler, and it has two arguments: an object called sender and MyEventArgs called e. We will define MyEventArgs later. Note that the delegate must be declared outside of your control class.

  

public delegate void MyEventHandler(object sender, MyEventArgs e);

public class MyControl: UserControl

{

   ...

}

2. MyEventArgs in Step 1 is the object that contains the data that can be passed from the event sender (MyControl) to the event receiver. MyEventArgs must extend the System.EventArgs class. Therefore, you now have the following code:

  

public class MyEventArgs: EventArgs

{

  ...

}

 

public delegate void MyEventHandler(object sender, MyEventArgs e);

 

public class MyControl: UserControl

{

   ...

}

There is some implementation you need to write inside the MyEventArgs class, but we will leave it until later.

 

3. In your control class, declare an event called MyEvent.

 

 

public class MyEventArgs: EventArgs

{

  ...

}

 

public delegate void MyEventHandler(object sender, MyEventArgs e);

 

public class MyControl: UserControl

{

  public event MyEventHandler MyEvent;

   ...

}

4. In your control class, declare a protected virtual method named On plus the name of the event. Since our event in this example is called MyEvent, the method is called OnMyEvent. Note that OnMyEvent has one argument of type MyEventArgs. Inside of this method, you raise the event. In C#, raising an event is achieved by calling the event name. To raise the event, you pass two arguments: the sender (the control MyControl) and the MyEventArgs object passed to the method.

 

 

public class MyEventArgs: EventArgs

{

  ...

}

 

public delegate void MyEventHandler(object sender, MyEventArgs e);

 

public class MyControl: UserControl

{

  public event MyEventHandler MyEvent;

  protected virtual void OnMyEvent(MyEventArgs e)

  {

    MyEvent(this, e)

  }

   ...

}

5. Now, the only step left is to actually call OnMyEvent from somewhere in the MyControl class. How you do this depends on what should cause the event to occur. This will become clear in the next section, when I present the real control that implements two events. Afterwards, users of your control can consume the MyEvent event in your control by wiring the event to an event handler in their form, as shown at the beginning of this article. Now, let's see the real code with two events and demonstrate how these events can be raised and consumed.

 

  

 

Post a Comment