Click here to Skip to main content
12,830,941 members (42,249 online)
Click here to Skip to main content
Add your own
alternative version


79 bookmarked
Posted 5 May 2011

Delegates 101 - Part I: What is a Delegate?

, 15 Jun 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
What is a Delegate?


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" 
<html xmlns="">
    <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>
        Simple Calculator</h1>
        <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>
        <input id="intRight" type="text" style="width: 50px;" /> 
        <input id="calculate" type="button" value="Calculate" />
    <hr />
        <label for="result">
            Result:</label><input id="result" type="text" 
		style="width: 150px;" disabled="disabled" />

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;
            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);

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;
        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
        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.


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


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


About the Author

Web Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Monjurul Habib11-Sep-12 10:47
memberMonjurul Habib11-Sep-12 10:47 
GeneralMy vote of 5 Pin
Nigam Patel2-Jan-12 2:09
memberNigam Patel2-Jan-12 2:09 
GeneralMy vote of 5 Pin
Pranit Kothari23-Dec-11 20:01
memberPranit Kothari23-Dec-11 20:01 
GeneralMy vote of 5 Pin
Mahsa Hassankashi11-Jul-11 23:41
memberMahsa Hassankashi11-Jul-11 23:41 
GeneralMy vote of 5 Pin
CS14015-Jul-11 23:43
memberCS14015-Jul-11 23:43 
GeneralMy vote of 5 Pin
AnoopPA23-Jun-11 2:02
memberAnoopPA23-Jun-11 2:02 
GeneralMy vote of 5 Pin
baldgeek21-Jun-11 6:41
memberbaldgeek21-Jun-11 6:41 
GeneralMy vote of 5 Pin
Mamun Reza21-Jun-11 1:53
memberMamun Reza21-Jun-11 1:53 
GeneralGreat article! Pin
mikemkii21-Jun-11 0:05
membermikemkii21-Jun-11 0:05 
GeneralMy vote of 5 Pin
Monjurul Habib17-Jun-11 11:37
memberMonjurul Habib17-Jun-11 11:37 
GeneralMy vote of 5 Pin
kkbandi16-Jun-11 5:58
memberkkbandi16-Jun-11 5:58 
GeneralMy vote of 5 Pin
Rhuros15-Jun-11 22:49
memberRhuros15-Jun-11 22:49 
GeneralMy vote of 5 Pin
Balu Sathish14-Jun-11 21:32
memberBalu Sathish14-Jun-11 21:32 
GeneralMy vote of 5 Pin
Morl9914-Jun-11 2:37
memberMorl9914-Jun-11 2:37 
GeneralAwesome Articles Pin
S Gnana Prakash17-May-11 11:34
memberS Gnana Prakash17-May-11 11:34 
GeneralMy vote of 4 Pin
afaz14-May-11 18:58
memberafaz14-May-11 18:58 
GeneralMy vote of 5 Pin
Cadu Sa Motta11-May-11 6:41
memberCadu Sa Motta11-May-11 6:41 
GeneralYet another vote of 5 Pin
Phil Wheeler10-May-11 1:22
memberPhil Wheeler10-May-11 1:22 
GeneralMy vote of 5 Pin
daroczy9-May-11 19:29
memberdaroczy9-May-11 19:29 
GeneralMy 5 Pin
o1010wanabe9-May-11 12:47
membero1010wanabe9-May-11 12:47 
GeneralMy vote of 5 Pin
Prasanta_Prince7-May-11 21:36
memberPrasanta_Prince7-May-11 21:36 
GeneralMy vote of 5 Pin
T_uRRiCA_N5-May-11 21:07
memberT_uRRiCA_N5-May-11 21:07 
GeneralMy vote of 5 Pin
saxenaabhi65-May-11 15:28
membersaxenaabhi65-May-11 15:28 
GeneralMy vote is 5 Pin
Shahriar Iqbal Chowdhury5-May-11 11:34
memberShahriar Iqbal Chowdhury5-May-11 11:34 
GeneralMy vote of 5 Pin
AspDotNetDev5-May-11 11:03
mvpAspDotNetDev5-May-11 11:03 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 16 Jun 2011
Article Copyright 2011 by MBigglesworth79
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid