callbackDelegate result = ResultCallback;
AddTwoNumbers(5, 3, result);
Console.ReadLine();
}
static private void AddTwoNumbers(
int num1, int num2, callbackDelegate callback) {
int result = num1 + num2;
callback('The result is: ' + result.ToString());
}
static private void ResultCallback(string Message) {
Console.WriteLine(Message);
}
}
First, you declare two methods:
□ AddTwoNumbers()
— Takes in two integer arguments and a delegate of type callbackDelegate
□ ResultCallback()
— Takes in a string argument and displays the string in the console window
Then you declare a delegate type:
delegate void callbackDelegate(string Message);
Before you call the AddTwoNumbers()
function, you create a delegate of type callbackDelegate
and assign it to point to the ResultCallback()
method. The AddTwoNumbers()
function is then called with two integer arguments and the result
callback delegate:
callbackDelegate result = ResultCallback;
AddTwoNumbers(5, 3, result);
In the AddTwoNumbers()
function, when the calculation is done, you invoke the callback
delegate and pass to it a string:
static private void AddTwoNumbers(
int num1, int num2, callbackDelegate callback) {
int result = num1 + num2;
}
The callback
delegate calls the ResultCallback()
function, which prints the result to the console. The output is:
The result is: 8
Asynchronous Callbacks
Callbacks are most useful if they are asynchronous. The callback illustrated in the previous example is AddTwoNumbers()
function takes a long time to execute, all the statements after it will block. Figure 7-1 shows the flow of execution when the callback is synchronous.

Figure 7-1
A better way to organize the program is to call the AddTwoNumbers()
method asynchronously, as shown in Figure 7-2. Calling a function asynchronously allows the main program to continue executing without waiting for the function to return.

Figure 7-2
In this asynchronous model, when the AddTwoNumbers()
function is called, the statement(s) after it can continue to execute. When the function finishes execution, it calls the ResultCallback()
function.
Here's the rewrite of the previous program, using an asynchronous callback:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegates {
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
//---method to add two numbers---
static private int AddTwoNumbers(int num1, int num2) {
return num1 + num2;
}
}
}
First, you define a delegate type so that you can point to the AddTwoNumbers()
method:
delegate int MethodDelegate(int num1, int num2);
Then create a delegate, and assign it to point to the AddTwoNumbers()
method: