Click here to Skip to main content
Click here to Skip to main content

Delegates 101 - Part I: What is a Delegate?

By , 15 Jun 2011
Rate this:
Please Sign up or sign in to vote.

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 an operator from the drop-down and inputs an integer on 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;" /> 
        <select id="operator">
            <option value="+">Add</option>
            <option value="-">Subtract</option>
            <option value="*">Multiply By</option>
            <option value="/">Divide By</option>
        </select> 
        <input id="intRight" type="text" style="width: 50px;" /> 
        <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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

MBigglesworth79
Web Developer
United Kingdom United Kingdom
No Biography provided
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMonjurul Habib11-Sep-12 9:47 
GeneralMy vote of 5 PinmemberNigam Patel2-Jan-12 1:09 
GeneralMy vote of 5 PinmemberPranit Kothari23-Dec-11 19:01 
GeneralMy vote of 5 PinmemberMahsa Hassankashi11-Jul-11 22:41 
GeneralMy vote of 5 PinmemberCS14015-Jul-11 22:43 
GeneralMy vote of 5 PinmemberAnoopPA23-Jun-11 1:02 
GeneralMy vote of 5 Pinmemberbaldgeek21-Jun-11 5:41 
GeneralMy vote of 5 PinmemberMamun Reza21-Jun-11 0:53 
GeneralGreat article! Pinmembermikemkii20-Jun-11 23:05 
GeneralMy vote of 5 PinmemberMonjurul Habib17-Jun-11 10:37 
GeneralMy vote of 5 Pinmemberkkbandi16-Jun-11 4:58 
GeneralMy vote of 5 PinmemberRhuros15-Jun-11 21:49 
GeneralMy vote of 5 PinmemberBalu Sathish14-Jun-11 20:32 
GeneralMy vote of 5 PinmemberMorl9914-Jun-11 1:37 
GeneralAwesome Articles PinmemberS Gnana Prakash17-May-11 10:34 
GeneralMy vote of 4 Pinmemberafaz14-May-11 17:58 
GeneralMy vote of 5 PinmemberCadu Sa Motta11-May-11 5:41 
GeneralYet another vote of 5 PinmemberPhil Wheeler10-May-11 0:22 
GeneralMy vote of 5 Pinmemberdaroczy9-May-11 18:29 
GeneralMy 5 Pinmembero1010wanabe9-May-11 11:47 
GeneralMy vote of 5 PinmemberPrasanta_Prince7-May-11 20:36 
GeneralMy vote of 5 PinmemberT_uRRiCA_N5-May-11 20:07 
GeneralMy vote of 5 Pinmembersaxenaabhi65-May-11 14:28 
GeneralMy vote is 5 PinmemberShahriar Iqbal Chowdhury5-May-11 10:34 
GeneralMy vote of 5 PinmvpAspDotNetDev5-May-11 10:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 16 Jun 2011
Article Copyright 2011 by MBigglesworth79
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid