Aug 8, 2015

Delegate Tutorial

1. Define the Delegate
2. Create an Object of the Delegate and assign a method to it
3. Invoke the Delegate
Invocation of the Delegate is the same as the invocation of the
 method that is encapsulate in the Delegate.

Let’s take a sample example. Consider a function that accepts two numbers and adds them.

Let’s create a Delegate that points to an Add function.

Define the Delegate

delegate void PointToAdd(int numberOne,int numberTwo);

 Create an object of the Delegate and assign a method to it

 PointToAdd pointToAdd = AddTwoNumber;

 Invoke a Delegate

 pointToAdd.Invoke(10, 20);


 Now let’s look at a complete sample at once.


 class DelegateDemo1

    delegate void PointToAdd(int numberOne,int numberTwo);
    static void Main(string[] args)
    {
        PointToAdd pointToAdd = AddTwoNumber;
        pointToAdd.Invoke(10, 20);
        Console.Read();
    }
    static void AddTwoNumber(int numberOne,int numberTwo)
    {
        Console.WriteLine((numberOne+numberTwo).ToString());
    }
}



Invocation of the Delegate is the same as the invocation of the method 
that is encapsulate by the Delegate. So is it true that we can replace the Delegate with a simple method invocation?



What advantage does a Delegate have over a method invocation?

The developer can assign a method to a Delegate during runtime. Do you remember pointers in C?
 A Delegate is nothing but a pointer to a function. When developers are not aware which function to call or 
 a function call is based on a condition, they can choose a delegate to call the function during run time.

Let’s take sample example. Similar to our above example we will create functions for adding, subtracting, division, and multiplication of two numbers.

We give the choice to the user to enter two numbers and a string, adds for addition, subs for subtraction, and div for division of two numbers.

Let’s define the Delegate that supports a simple math operation of two numbers.


public delegate void PointToMathsOperation(int numberOne, int numberTwo);
PointToMathsOperation pointToMathsOperation = null;


We have assigned the Delegate to null. We will assign a method to the 
Delegate dynamically or at run time. We have the following methods matching the delegate signature.


private void Add(int numberOne, int numberTwo)
{
    Console.WriteLine((numberOne + numberTwo).ToString());
}

private void Sub(int numberOne, int numberTwo)
{
    Console.WriteLine((numberOne - numberTwo).ToString());
}

private void Div(int numberOne, int numberTwo)
{
    Console.WriteLine((numberOne / numberTwo).ToString());
}

private void Mul(int numberOne, int numberTwo)
{
    Console.WriteLine((numberOne * numberTwo).ToString());
}

Let's write a method that will assign a method to the Delegate based on the user choice and return the object of the Delegate.


public PointToMathsOperation Operation(string operationName)
{
    switch (operationName)
    {
        case "Add":
            pointToMathsOperation = Add;
            return pointToMathsOperation;
        case "Sub":
            pointToMathsOperation = Sub;
            return pointToMathsOperation;
        case "Div":
            pointToMathsOperation =Mul;
            return pointToMathsOperation;
        case "Mul":
            pointToMathsOperation = Div;
            return pointToMathsOperation;
    }
    return pointToMathsOperation;
}


Let's take a compete look at what we have done so far. We have defined a Math class as follows:

public class Math
{
    public delegate void PointToMathsOperation(int numberOne, int numberTwo);
    PointToMathsOperation pointToMathsOperation = null;
    public PointToMathsOperation Operation(string operationName)
    {
        
        switch (operationName)
        {
            case "Add":
                pointToMathsOperation = Add;
                return pointToMathsOperation;
            case "Sub":
                pointToMathsOperation = Sub;
                return pointToMathsOperation;
            case "Div":
                pointToMathsOperation =Mul;
                return pointToMathsOperation;
            case "Mul":
                pointToMathsOperation = Div;
                return pointToMathsOperation;
        }
        return pointToMathsOperation;
    }
    private void Add(int numberOne, int numberTwo)
    {
        Console.WriteLine((numberOne + numberTwo).ToString());
    }
    private void Sub(int numberOne, int numberTwo)
    {
        Console.WriteLine((numberOne - numberTwo).ToString());
    }
    private void Div(int numberOne, int numberTwo)
    {
        Console.WriteLine((numberOne / numberTwo).ToString());
    }
    private void Mul(int numberOne, int numberTwo)
    {
        Console.WriteLine((numberOne * numberTwo).ToString());
    }
}

Let's instantiate the Math class and call the method Operation that returns the Delegate object.
 We can invoke the Delegate by passing two numbers to it as per the delegate signature. 

 public class DelegateDemo2
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Please enter two number:-");
        var numberOneString = Console.ReadLine();
        var numberTwoString = Console.ReadLine();
        Console.WriteLine("Please enter operation to perform like add,mul,sub and div :-");
        var choice = Console.ReadLine();
        int numberOne, numberTwo;
        Math math = new Math();
        int.TryParse(numberOneString,out numberOne);
        int.TryParse(numberTwoString,out numberTwo);
        math.Operation(choice).Invoke(numberOne,numberTwo);
        Console.ReadLine();
    }
}

What is a Multicast Delegate?

Multicast Delegate is an extension of a Delegate. You can assign multiple methods to a Delegate object 
and invoke them during Delegate invocation. Methods get invoked in the 
same hierarchy in which they get assigned to the Delegate object.

Let’s take a simple example. 

Consider a system that will broadcast messages when 
it fails doing transactions. The system will broadcast a message to the Admin via SMS on mobile, 
email on mailbox, and message on fax. 
For simplicity we will build a console application which accepts a string from the user, 
any string content other than “Pass” assumes that the transaction has failed, and we 
broadcast a message to the admin using a Multicast Delegate.

Let’s build a BroadCast class that contains a method to transmit a 
message to the admin via SMS on mobile, email on mailbox, and message on fax.

public class BroadCast
{
    public void ViaMessage()
    {
        Console.WriteLine("Message Send to mobile.");
    }

    public void ViaEmail()
    {
        Console.WriteLine("Email send to mailbox.");
    }

    public void ViaFax()
    {
        Console.WriteLine("Message send via fax.");
    }
}

Our system can broadcast a message using the above media. 
Let’s build a system that will broadcast a message when it fails using a Multicast Delegate.

/// <summary>
/// Multicast Delegate
/// </summary>
public class DelegateDemo3
{
    //Deligate declaration
delegate void SendMessage();

    public static void Main(string[] args)
    {
        BroadCast broadCast=new BroadCast();
        SendMessage sendMessage = broadCast.ViaEmail;
        sendMessage += broadCast.ViaFax;
        sendMessage += broadCast.ViaMessage;
        Console.WriteLine("Enter trascation suncess.");
        var result = Console.ReadLine();
        if (result.Equals("Pass"))
        {
            Console.WriteLine("Successfull trasaction!");
        }
        else
        {
            Console.WriteLine("Transaction fail !");
            sendMessage.Invoke();
        }
        Console.ReadLine();
    }
}


No comments:

Post a Comment