A delegate is a C# type that is a reference to a method. Delegates are something like function pointers in C++ and variables that point to functions in scripting languages like JavaScript but more strongly typed. The main use of delegates is for callbacks. The same thing can be acheived with interfaces but delegates are more concise. Here an example that uses a delegate for logging messages. The example implementation logs to the console but a real implementation in a web environment would log to a file.
In this example the code using the delegate has full knowledge of the implementation. In a real example the delegate would be passed in as a parameter leaving the calling code independent of the implementation of the callback. An example of this type of use in bioinformatics might be a long running search. The calling code may wish to be notified every time a match was found without having to make the user wait.
A delegate type can be assigned more than one method and will call all assigned methods when invoked.
This is referred to as multicasting in the C# literature.
To assign more than one method to a delegate use the + operator. Use the
- operator to remove a delegate. The operators += and
-= work in an intuitive way with delegates. Multicasting with delegates is
used extensively in event handling in C#.
Anonymous methods can also be assigned to delegates. An anonymous method is a code block without a method name. Here is a program that illustrates use of an anonymous method as a delegate.
In this example the code that calls the delegate in the LongRunningSearch
class is not aware of the impementation. It simply calls the delegate whenever
a match is found. The program also illustrates the concept of a captured varable.
The variable matchCount is declared outside of the anonymous method but is
still accessible. This is a useful technique to use to pass context information with the
callback. The output from this program is:
There are no user comments.
Please send ideas and opinions by email at alexamies@gmail.com.