Search

Tuesday 3 May 2011

Delegates 101 - Part I: What is a Delegate?


Introduction

OK, so what has prompted me to start writing a basic tutorial series; and why on delegates? Well, the answer is quite simple: I have found few (if any) articles on the Web which actually do a good job of explaining what delegates are in .NET and how they can be used. Nearly every article I have read (and there have been a few) go into great depths about event-handling and how delegates are used in that scenario; whilst neglecting to cover the basics. Important though it is, event handling is not a delegate's raison d'ĂȘtre.

It's little wonder, therefore, that I have seen many a trainee/junior developer (myself included, back in the day...) scratching their heads and looking somewhat befuddled when trying to get their minds round concepts such as passing methods as parameters, and lambda expressions.

As a result, this article will specifically not cover event handling but instead will be, for the moment, sticking with the basics of .NET delegates

An Example in JavaScript

I'm going to start with an example in JavaScript, in the hope that it will make explanations easier when we move onto a .NET example.

The following is a simple calculator. The user selects and operator from the drop-down and inputs an integer in either side. When the user clicks the 'Calculate' button, the result of the simple sum is output on the page. Here is the HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple Calculator</title>
    <script src="../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="../Scripts/SimpleCalc.js" type="text/javascript"></script>
</head>
<body>
    <h1>
        Simple Calculator</h1>
    <div>
        <input id="intLeft" type="text" style="width: 50px;" />&nbsp;
        <select id="operator">
            <option value="+">Add</option>
            <option value="-">Subtract</option>
            <option value="*">Multiply By</option>
            <option value="/">Divide By</option>
        </select>&nbsp;
        <input id="intRight" type="text" style="width: 50px;" />&nbsp;
        <input id="calculate" type="button" value="Calculate" />
    </div>
    <hr />
    <div>
        <label for="result">
            Result:</label><input id="result" type="text" style="width: 150px;" disabled="disabled" />
    </div>
</body>
</html>

And the JavaScript which performs the calculation is broken down as follows. Firstly we have four functions which perform each type of mathematical operation:

function add(int1, int2) {
    return int1 + int2;
}

function subtract(int1, int2) {
    return int1 - int2;
}

function multiply(int1, int2) {
    return int1 * int2;
}

function divide(int1, int2) {
    return int1 / int2;
}

OK, nothing magical there. What is more interesting is what we do when the 'Calculate' button is clicked:

$(document).ready(function () {
    $("#calculate").click(function () {
        var left = parseInt($("#intLeft").val())
        var right = parseInt($("#intRight").val());
        var operator = $("#operator").val();
        var mathFunc;
        if (operator === '+')
            mathFunc = add;
        else if (operator === '-')
            mathFunc = subtract;
        else if (operator === '*')
            mathFunc = multiply;
        else
            mathFunc = divide;
        printResult(mathFunc, left, right);
    });
});

As you can see, we first parse the two integers from the textboxes and get the chosen operator from the drop-down. Next we declare the variable mathFunc. Now since JavaScript is a weakly-typed language we can assign just about anything we like to a variable, including functions. We then perform some simple logic to assign the appropriate function to the variable. Note the lack of parentheses ('(' and ')') when assigning the function. This is how we assign the function itself to the variable instead of the result of calling it.

Next we call the printResult() function, passing in our mathFunc variable as well as the two integers:

function printResult(mathFunc, int1, int2) {
    var result = mathFunc(int1, int2);
    $("#result").val(result);
}

This function calls the function we have passed to it, and outputs the result to the page.

Now for some .NET

Now we can do exactly the same thing in .NET and for this illustration I am going to use a console application which takes the two integers and the operator as arguments (e.g.: SimpleCalc.exe 10 + 7)

Again we have our basic mathematical functions:

// C#
static int Add(int int1, int int2)
{
    return int1 + int2;
}

static int Subtract(int int1, int int2)
{
    return int1 - int2;
}

static int Multiply(int int1, int int2)
{
    return int1 * int2;
}

static int Divide(int int1, int int2)
{
    return int1 / int2;
}
' Visual Basic
Function Add(ByVal int1 As Integer, ByVal int2 As Integer) As Integer
    Return int1 + int2
End Function

Function Subtract(ByVal int1 As Integer, ByVal int2 As Integer) As Integer
    Return int1 - int2
End Function

Function Multiply(ByVal int1 As Integer, ByVal int2 As Integer) As Integer
    Return int1 * int2
End Function

Function Divide(ByVal int1 As Integer, ByVal int2 As Integer) As Integer
    Return CInt(int1 / int2)
End Function

But in a strongly-typed environment, such as .NET, how do we assign a method to a variable? What should the type of such a variable be? Well, this is where delegates come in. Essentially a delegate can be thought of as another custom type which specifies the signature of a method which can be assigned to variables of that type. We declare our delegate as follows:

// C#
delegate int MathFunction(int int1, int int2);
' Visual Basic
Delegate Function MathFunction(ByVal int1 As Integer, ByVal int2 As Integer) As Integer

As you can see, the signature of the delegate matches the signatures of our four functions. We are saying that any variable of type MathFunction can only be assigned a method which takes two integers as parameters and returns an integer.

Now if we look at our PrintResult() method:

// C#
static void PrintResult(MathFunction mathFunction, int int1, int int2)
{
    int result = mathFunction(int1, int2);
    Console.WriteLine(String.Format("Result is {0}", result));
}
' Visual Basic
Sub PrintResult(ByVal mathFunction As MathFunction, ByVal int1 As Integer, ByVal int2 As Integer)
    Dim result As Integer = mathFunction(int1, int2)
    Console.WriteLine(String.Format("Result is {0}", result))
End Sub

Here we see the mathFunction parameter is of type MathFunction and so accepts one of our functions. As with the JavaScript example, the method calls the function passed to it and outputs the result.

Finally, the Main() method of our console application:

// C#
static void Main(string[] args)
{
    int left = int.Parse(args[0]);
    char theOperator = args[1][0];
    int right = int.Parse(args[2]);
    MathFunction mathFunction;
    if (theOperator == '+')
        mathFunction = Add;
    else if (theOperator == '-')
        mathFunction = Subtract;
    else if (theOperator == '*')
        mathFunction = Multiply;
    else
        mathFunction = Divide;
    PrintResult(mathFunction, left, right);
}
' Visual Basic
Sub Main(ByVal args() As String)
    Dim left As Integer = Integer.Parse(args(0))
    Dim theOperator As Char = args(1)(0)
    Dim right As Integer = Integer.Parse(args(2))
    Dim mathFunction As MathFunction
    If theOperator = "+" Then
        mathFunction = AddressOf Add
    ElseIf theOperator = "-" Then
        mathFunction = AddressOf Subtract
    ElseIf theOperator = "*" Then
        mathFunction = AddressOf Multiply
    Else
        mathFunction = AddressOf Divide
    End If
    PrintResult(mathFunction, left, right)
End Sub

Again, as in our JavaScript example, we declare a variable to hold our function and then perform some simple logic to assign the correct function. This, along with the two integers, is then passed to our PrintResult() method for output to the console.

Summary

In the strongly-typed .NET environment, delegates provide the means by which a variable or parameter can be specified as accepting a method with a particular signature.

Next: Anonymous Methods and Lambdas

12 comments:

  1. very nice article... keep it up!

    ReplyDelete
  2. Why do we want to use delegates?

    I mean, what added benefit do you get with :

    If theOperator = "+" Then
    mathFunction = AddressOf Add
    ElseIf theOperator = "-" Then
    mathFunction = AddressOf Subtract

    over

    If theOperator = "+" Then
    mathFunction = Add()
    ElseIf theOperator = "-" Then
    mathFunction = Subtract()

    ?

    ReplyDelete
  3. You are absolutely right, if this were a "real" scenario then that is exactly what I would do too; as using a delegate for doing some simple maths would be somewhat overkill! However, for the purposes of demonstration, I like to try and keep my examples as simplistic as possible.

    ReplyDelete
  4. Apologies. Let me rephrase:

    Do you have a real life example of when delegates were used to some benefit?
    I'm (obviously) new to this so I'm interested to hear possible applications of this delegation.

    ReplyDelete
    Replies
    1. Maybe a little late, but to find another real life example about when a delegate makes sense you may refer to http://www.dotmaniac.net/function-properties-for-more-flexible-classes/

      @MrBigglesorth: nice introduction! Thank you.

      Delete
  5. I'm not a big fan of using real-world examples, as they are usually too domain-specific to be of any use to the reader. However, the following is an outline of something I worked on where the requirement was that if a call to a method produced an error, then the application automatically took a screenshot:

    C#:

    public static void TakeScreenshotOnError(Action action)
    {
    try
    {
    action();
    }
    catch (Exception ex)
    {
    // Screen grabbing code goes here.
    throw; // Re-throw the exception.
    }
    }

    public static void PerformActions()
    {
    TakeScreenshotOnError(AnAction); // Does not throw an error.
    TakeScreenshotOnError(AnotherAction); // Throws a DivideByZeroException.
    }

    public static void AnAction()
    {
    int i = 2 + 2;
    }

    public static void AnotherAction()
    {
    int i = 6;
    int j = 0;
    int k = i / j;
    }

    Visual Basic:

    Public Shared Sub TakeScreenshotOnError(ByVal action As Action)
    Try
    action()
    Catch ex As Exception
    ' Screen grabbing code goes here.
    Throw ' Re-throw the exception.
    End Try
    End Sub

    Public Shared Sub PerformActions()
    TakeScreenshotOnError(AddressOf AnAction) ' Does not throw an error.
    TakeScreenshotOnError(AddressOf AnotherAction) ' Throws a DivideByZeroException.
    End Sub

    Public Shared Sub AnAction()
    Dim i As Integer = 2 + 2
    End Sub

    Public Shared Sub AnotherAction()
    Dim i As Integer = 6
    Dim j As Integer = 0
    Dim k As Integer = i / j
    End Sub

    ReplyDelete
  6. So is a delegate really just a function pointer? I'm pretty sure I could rewrite the example in C++ using function pointers. The only thing that delegates might offer (that I can see) is perhaps simpler syntax. Or is there more to it than that?

    ReplyDelete
  7. Nope, that's exactly what a delegate is. As you say, it's the .NET equivalent of a function pointer.

    ReplyDelete
  8. Well, it's better than a function pointer, in that the CLR and compiler enforces type safety. The method that is the target of the delegate invocation must match the delegate signature.

    ReplyDelete
  9. Excellent!

    Though using args[] is not comfortable for running in debug mode of Visual Studio

    ReplyDelete
  10. i am Geting exception on int left = Convert.ToInt32(args[0]); that firt line of main method that exception is "Index was outside the bounds of the array. " please help how can i fixed it .

    ReplyDelete