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:
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;
}
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:
delegate int MathFunction(int int1, int int2);
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:
static void PrintResult(MathFunction mathFunction, int int1, int int2)
{
int result = mathFunction(int1, int2);
Console.WriteLine(String.Format("Result is {0}", result));
}
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:
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);
}
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