Delegates

Delegates are types that hold references to methods instead of variables. A delegate can copy the behavior of any method. To declare a delegate, you use the delegate keyword. Declaring a delegate is similar to declaring a method except that it has no body. It has a return type and a set of parameters just like a method. These tells the type of method it can hold. Below shows the syntax of declaring a delegate.

delegate returnType DelegateName(dt param1, dt param2, ... dt paramN);

The following example program shows how to use and the benefits of using a delegate.

using System;

namespace DelegatesDemo
{
    public class Program
    {
        delegate void ArithmeticDelegate(int num1, int num2);

        static void Add(int x, int y)
        {
            Console.WriteLine("Sum is {0}.", x + y);
        }

        static void Subtract(int x, int y)
        {
            Console.WriteLine("Difference is {0}.", x - y);
        }

        static void Main()
        {
            ArithmeticDelegate Operation;

            int num1, num2;

            Console.Write("Enter first number: ");
            num1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter second number: ");
            num2 = Convert.ToInt32(Console.ReadLine());

            if (num1 < num2)
            {
                Operation = new ArithmeticDelegate(Add);
            }
            else
            {
                Operation = new ArithmeticDelegate(Subtract);
            }

            Operation(num1, num2);
        }
    }
}

Figure 1

Enter first number: 3
Enter second number: 5
Sum is 8
Enter first number: 5
variable = new DelegateName(MethodName);
Enter second number: 3 Difference is 2

Line 7 is the declaration of our delegate. We used the delegate keyword to indicate that it is a delegate. The following is the return type of the method it will accept. The naming practice for a delegate is the same with the method, we used Pascal Casing. We also append the word “Delegate” for better recognition. We defined the parameters of the delegate which will also be the same with the parameters of the method it will hold. The delegate that was declared in line 7 can only accept references to methods that has a void return type (no return type) and has two int parameters.

After defining the delegate, we defined two methods with exactly the same signature as the delegate because they are the methods the delegate will use later. Both methods don’t return a data and both accepts 2 int arguments. Inside the Main method, we declared a variable with the type of the delegate we defined (line 21). This variable will hold a reference to a method that matches the delegate’s signature.The program asked for two values from the user. We entered an if statement in line 31 wherein, if the value of the first number is less than the second number, then we add them. If the value of the first number is greater than or equal to the number, we subtract them. To assign a method to the delegate, we follow this syntax:

When assigning a delegate with a reference of the method, we use the new keyword followed by the name of the delegate. Inside the parentheses, we indicate the name of the method the delegate will refer to. A much simpler way is you can just assign the name of the method to the delegate variable.

Operation = Add;
Operation = Subtract;

Back to our if statement, when the condition was true, we assigned the delegate the method Add() and when the value was false, we assigned it with the Subtract() method. Line 40 executes our delegate containing the reference of the assigned method. Executing the delegate also executes the method it refers.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *