Lecture
Delegate (English delegate) - a data structure that points to methods (static or class instance) in the .NET Framework [1] [2] [3] [4].
Delegates are used, in particular, to define a prototype callback function, for example, in the .NET Framework event model.
Description
From the declaration of the delegate type, the compiler generates a class derived from System.MulticastDelegate. Thus, the signature of a function that takes a delegate as an argument might look like this:
public MyFunction (Delegate anotherFunction);
An additional feature of delegates is that they can be called asynchronously using the BeginInvoke () method. In this case, a free one is selected in the thread pool and the specified function is executed in parallel in its context. It is worth noting, however, that the number of threads in the pool is limited (there are 25 in the current implementation of .NET), and other calls will wait for their turn.
Example of declaring and using a delegate
using System;
// Delegate declaration
delegate void MyDelegate (string a);
class DelegateExample
{
static void Func (string param)
{
Console.WriteLine ("The function was called with parameter {0}.", Param);
}
public static void Main ()
{
// Create delegate instance
MyDelegate f = new MyDelegate (Func);
// function call
f ("hello");
}
}
The example outputs to the console the string "The function was called with the hello parameter.".
Comments
To leave a comment
Object oriented programming
Terms: Object oriented programming