Friday, January 7, 2011

Understanding the Delegates in console Application.

A delegate is a reference type variable, which holds the reference to a method. This reference can be changed at run-times, as desired. Although, delegates are a general-purpose mechanism for indirectly calling methods at runtime, their primary use in c# programming is for implementing events and the call-back methods.

Declaring Delegates:
The methods that can be referenced by a delegate are determined by the delegate declaration. The delegate can refer to the methods, which have the same signature as that of the delegate.
Consider the following example of delegate declaration:
public delegate void mydelegate(string s);

The declared delegate type can be used to reference any method. This method should have a single parameter of string type and it does not return any value.

The following syntax is used for delegate declaration:

Instantiating Delegate:
Create the delegate object of the delegate type, which you have alredy created. Assign the address of the required method to the delegate object. This can be done by calling the constructor of the delegate class and passing the method name.
The following example shows how to assign the address of a method to a delegate variable:
public void DelegateFunction(string passValue);
      // method implementation Here

    // Delegate Declaration
    public delegate void  Mydelegate(string ArgValue);

    public void UseMethod()
    //Delegate Instantiation
    MyDelegate DelegateObject = new MyDelegate(DelegateFunction);  
Note:-  The signature and return type of DelegateFunction matches with the delegate declaration of the MyDelegate delegate. The MyDelegate delegate can hold the address of DelegateFunction.Delegateobject is delegate object of the type, MyDelegate. The address of the DelegateFunction is assigned to the Delegateobject by passing, the name of the function to the delegate constructor.

No comments:

Recent Posts