Sunday 19 August 2018

C#: Delegates

Delegate is a type safe reference pointer. A delegate points to a function, by using the delegate you can call the function. 

Delegates are reference types.

How to create a delegate?
By using the delegate keyword, you can create a delegate.

Syntax
public delegate returnType nameOfTheDelegate(arguments);

By using the delegate, you can point to a function which has similar signature.

Following step-by-step procedure explains simple delegate application.

Step 1: Define a function.

    public static void printMessage(String message)
    {
        Console.WriteLine(message);
    }

Step 2: Define delegate that has similar signature to the ‘printMessage’ function defined in step 1.

public delegate void MyPrintDelegate(String message);

Step 3: Define instance of delegate, by passing the method you want to call as an argument.

MyPrintDelegate delgateDemo = new MyPrintDelegate(printMessage);

Step 4: Now by using ‘delegateDemo’, you can call the metho printMessage.

delgateDemo("Hello World");

Program.cs

using System;

class Program
{
    public delegate void MyPrintDelegate(String message);

    public static void printMessage(String message)
    {
        Console.WriteLine(message);
    }

    static void Main(string[] args)
    {
        MyPrintDelegate delgateDemo = new MyPrintDelegate(printMessage);

        delgateDemo("Hello World");

    }
}


Output
Hello World

Note
The signature of the delegate must match to the signature of the function that this delegate points to. Because of this delegate is called type safe reference pointer.

Main advantage of delegates is, you can decouple the core logic. So the applications that are going to user your code, can reuse the core logic.

Let’s see it by an example. Suppose you had written two methods to print even numbers, odd numbers like below.

   public static void printEventNumbers(int start, int stop)
    {
        for(int i=start; i < stop; i++)
        {
            if(i % 2 == 0)
            {
                Console.WriteLine(i);
            }
        }
    }

    public static void printOddNumbers(int start, int stop)
    {
        for(int i=start; i < stop; i++)
        {
            if(i % 2 != 0)
            {
                Console.WriteLine(i);
            }
        }
    }

Closely observe the above code snippet, there is a commonality in both the methods printEventNumbers & printOddNumbers. Both the methods check for a condition, if they satisfy the condition they are printing the number. By using delegates, we can make the application more generic.


You can define a function that takes a delegate as argument. If the delegate satisfy the condition, then print the data. Following is my printData definition.

    public static void printData(int start, int stop, IsSatisfied myDelegate)
    {
        for(int i=start; i < stop; i++)
        {
            if (myDelegate(i))
            {
                Console.WriteLine(i);
            }
        }
    }


Following is my delegate definition, it takes a number as argument and return true, if it satisfy given condition, else false.

public delegate bool IsSatisfied(int num);

Following are the functions to check whether given number is even (or) odd.

    public static bool isEven(int num)
    {
        return num % 2 == 0;
    }

    public static bool isOdd(int num)
    {
        return num % 2 != 0;
    }


Following statements print the even numbers.

IsSatisfied evenDelegate = new IsSatisfied(isEven);
printData(0, 10, evenDelegate);
                 
Following statements print the odd numbers

IsSatisfied oddDelegate = new IsSatisfied(isOdd);
printData(0, 10, oddDelegate);

Following is the complete working application.


Program.cs

using System;

class Program
{
    public delegate bool IsSatisfied(int num);

    public static bool isEven(int num)
    {
        return num % 2 == 0;
    }

    public static bool isOdd(int num)
    {
        return num % 2 != 0;
    }

    public static void printData(int start, int stop, IsSatisfied myDelegate)
    {
        for(int i=start; i < stop; i++)
        {
            if (myDelegate(i))
            {
                Console.WriteLine(i);
            }
        }
    }
   
    static void Main(string[] args)
    {
        IsSatisfied evenDelegate = new IsSatisfied(isEven);
        IsSatisfied oddDelegate = new IsSatisfied(isOdd);

        printData(0, 10, evenDelegate);

        Console.WriteLine("**************");

        printData(0, 10, oddDelegate);
    }
}

Output
0
2
4
6
8
**************
1
3
5
7
9

Suppose if you want to print prime numbers, then you can write a isPrime function and reuse the printData method like below.

Public static bool isPrime(int number){
         //Implement logic
}
IsSatisfied primeDelegate = new IsSatisfied(isPrim);

printData(0, 10, primeDelegate);



Previous                                                 Next                                                 Home

No comments:

Post a Comment