Delegates in C#. An Overview

A delegate is a type that refers to a static method or an instance method, and then used to call this method.

Following code explains how to create and use a delegate.

Steps involved are

1)Define the delegate type to specify its signature.
2)Declaring the Delegate Variable
3)Initializing the Delegate Variable with reference to any function
4)Calling the function

public class Program
 {
    //Defining the Delegate type
    public delegate double ProcessDelegate(int param1, int param2);

    public static double Multiply(int param1, int param2)
       {
            return param1 * param2;
       }

    public static double Divide(int param1, int param2)
       {
            return param1 / param2;
       }

    public static void Main(string[] args)
     {
        
public static void Main(string[] args)
{
  //Declaring the Delegate Variable
  ProcessDelegate processDelegate;

//Initializing Delegate Variable with reference to Multiply function
  processDelegate = new ProcessDelegate(Multiply);

  double result;
  result = processDelegate(6, 3);   // Calling the Delegate
  Console.WriteLine(result);

//Initializing the Delegate Variable with reference to Divide function            
  processDelegate = new ProcessDelegate(Divide);

  result = processDelegate(6, 3);   // Calling the Delegate
  Console.WriteLine(result);

  //Initializing the Delegate Variable with reference to Sum function
  Addition testClass = new Addition();
  processDelegate = new ProcessDelegate(testClass.Sum);

  result = processDelegate(6, 3);   // Calling the Delegate
  Console.WriteLine(result);

  Console.ReadKey();
 }

}

    public class Addition
    {
        public double Sum(int a, int b)
        {
            return a + b;
        }
    }

Note:- Signature of the delegate and function should match for a delegate to refer to a function

Advertisements

1 Comment

  1. Jackson said,

    December 17, 2010 at 4:12 am

    Cool man .. Its really cool One 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: