Delegate in C#

Abhisek
Posted by in C# category on for Beginner level | Views : 8745 red flag

This article describes what is a delegate and how to use it with a simple delegate example. As delegate is a vast chapter you can not find the details of delegate in this article. This article just explains the key features and attribute of a C# delegate.
Delegate in C#
The Windows API makes frequent use of C-style function pointers to create entities termed "callback function" or simply "callbacks". Using callback programmers were able to configure one function to report back to(call back) another unction in this application.

         The problem with "callback" is that they represents a little more than a raw address in memory.Callbacks could be configured to include additional type-safe information such as no. of parameters & return value of the method pointed tools. But this is not the case in traditional callbacks and you may suspect,can therefore be a frequent source of bugs,hard crashes,& other runtime errors.
 
          In .NET callbacks are possible as they are really useful. But in .NET their functionality is accomplished in a much saver and more object-oriented manner using "Delegate". A "delegate" is a type-safe object that points to another method in the application,which can be invoked at later time.More specifically a delegate type contains three important information,
  1. The name of the method on which it makes calls.
  2. The arguments o this method.
  3. The return value of the method.
N:B:- .NET delegates can point to either static or instant methods.
  
      Once a delegate has been created and provided the required information, it may be dynamically invoke the methods it pointed to at runtime. Every .NET delegate is automatically endowed with the ability to call their methods synchronously or asynchronously. This simplifies programming tasks during creating multithreaded application.

Defining a Delegate in C#

        To define a delegate in C#, we have to use the 'delegate' keyword. You can give any name to your delegate.But you must define the delegate to match the signature of method it points to. For example, suppose you want to build a delegate named BinaryMath that can point to any method that returns an integer and takes two integers as input parameter, then the syntax will be,
 
public delegate int BinaryMath(int x,int y);

          When the C# compiler processes the delegate types,it automatically generates a sealed class derived from System.MulticastDelegate. This class provides the necessary infrastructure for the delegate to hold the list of methods to be invoked later. You can examine the BinaryMath delegates using "ildasm.exe",you would find the items shown in the figure,



           As you can see the BinaryMath class defines three public methods, Invoke() is the core method and is used to each method maintained by the Delegate type in a synchronous manner. Invoke() is called when you make use of the appropriate C# syntax.

      BeginInvoke() and EndInvoke() provide the ability to call the current method asynchronously on a second thread execution. Notice that the parameters and return type defined for Invoke() method exactly match the definition of BinaryMath delegate. The initial parameter to BeginInvoke() members are also based on the BinaryMath delegate; it will provide two final parameters that are used to facilitate asynchronous method invocation. Then the return value of EndInvoke() is identical to the original delegate declaration, and will always take as a sole parameter an object implementing the IASyncResult interface.

      Finally we conclude that C# delegate definition results in a sealed class with three compiler generated methods whose parameters and return values are dependent on the delegate declaration.

N.B.:- When we build a type using C# delegate keyword, we indirectly declaring a class type that derives from "System.Multicast" delegate obtains additional functionality from the parent class,"System.Delegate".

Example of C# delegate
using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleDelegate
{
// This delegate can point to any method taking two integers and returning an integer.
public delegate int BinaryMath(int x, int y);

public class SimpleMath
{
public int Add(int x, int y)
{ return x + y; }
public int Subtract(int x, int y)
{ return x - y; }
public static int SquareNumber(int a)
{ return a * a; }
}

class SimpleDelegate
{
static void Main(string[] args)
{
Console.WriteLine("***** A Simple Delegate Use *****\n");
// Create a BinaryOp object that points to SimpleMath.Add()
SimpleMath m = new SimpleMath();
BinaryMath b = new BinaryMath(m.Add);

//Display information about this object.
DisplayDelegateInfo(b);

// Invoke Add() method using delegate.
Console.WriteLine("\n15 + 30 is {0}", b(15, 30));
Console.ReadLine();
}

static void DisplayDelegateInfo(Delegate delObj)
{
// Print the names of each member in the delegates invocation list.
foreach (Delegate d in delObj.GetInvocationList())
{
Console.WriteLine("Method Name: {0}", d.Method);
Console.WriteLine("Target Name: {0}", d.Target);
}
}
}
}
Description

         Here the format of BinaryMath delegate is that, it can point to any method taking two integer value and returning an integer value. We have created a class SimpleMath which contains two static methods that match the pattern of the delegate.

          Then we are creating a object of the BinaryMath delegate which will point to the desired method in the SimpleMath class.

            We have simply pass the name of the method to the delegate's constructor. The Invoke() method is actually called here,
 Console.WriteLine("\n15 + 30 is {0}", b(15, 30));
            Here the run time actually call the compiler generated Invoke( )method. You can verify it by opening the assembly in ildasm.exe. See the below image,



      .NET delegates are type safe. If you will attempt to pass a delegate a method that does not "match the pattern", you will receive a compile time error. Suppose the SimpleMath class contains another method as SquareNo() as follows,
public class SimpleMath
{
  public static int SquareNo(int a)
 {
   return a* a;
 }
}
         If you will create the BinaryMath object which will point to SquareNo() method it will give the error "Method does not match delegate pattern!".
//will give error "Method does not match delegate pattern!"
BinaryMath b = new BinaryMath(SimpleMath.SquareNo(20));
        Just add another method named DisplayDelegateInfo() . It will print the names of the methods maintained by the System.Delegate derived type as well as the name of the class defining the method. To do this we have to iterate over the System.Delegate array returned by GetInvocationList(), invoking each object's target and method properties.
 static void DisplayDelegateInfo(Delegate delObj)
{
// Print the names of each member in the
// delegates invocation list.
foreach (Delegate d in delObj.GetInvocationList())
{
Console.WriteLine("Method Name: {0}", d.Method);
Console.WriteLine("Target Name: {0}", d.Target);
}
}
          In the output the type will not displayed by the Target property if our delegate points to the static method and therefore there id no object to reference. To display the type name just create an object of simple method class and call the method using this type as follows,
 // Create a BinaryOp object that points to SimpleMath.Add()
SimpleMath m = new SimpleMath();
BinaryMath b = new BinaryMath(m.Add);
        Run the application and you will see the following output as shown in the below figure. It will display the method name maintained in CIL and it's target.



        Delegate is a vast chapter in C# and there is a lot of use of delegate. Here I have just mention what a delegate is and how to use it in a simple manner. I have just given the basic information of C# delegates here.
    

Page copy protected against web site content infringement by Copyscape

About the Author

Abhisek
Full Name: Abhisek Panda
Member Level: Bronze
Member Status: Member
Member Since: 10/11/2009 6:25:59 AM
Country: India
Abhisek Panda

Thanks and Regards Abhisek Panda Go Green And Save Your Future

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)