Click here to Skip to main content
13,298,534 members (45,054 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
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
Nigam Patel2-Jan-12 2:09
memberNigam Patel2-Jan-12 2:09 

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
Web03 | 2.8.171207.1 | Last Updated 16 Jun 2011
Article Copyright 2011 by MBigglesworth79
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid