Why this article was written
At first, I want to make excuses for my knotty English. However, I shall do everything possible to make this article understandable.
At the second, I want to explain why I wrote this article. Some time ago, I had a discussion with a guy. This guy was leaning programming with C#. He asked me to explain about delegates and events. Actually, I was very surprised. There are a lot of good C# books, useful links, source code samples, and etc. However, during our discussion, I understood that this guy read books about C# programming, browsed suitable web resources, investigated good code samples, but still had questions about delegates!
The current code sample is the result of our discussion. This sample is very simple, it is possible to say, stupid. But, it helped my opponent to understand the essentials of delegates. I hope that this sample and comments will be useful for other people who are learning C# programming.
The article itself
I recommend downloading the demo project before reading the article. This is a C# console application. Unzip the downloaded file and click SLN file to launch the project in .NET Studio.
C# delegate is a callback function. In other words, delegate is a way to provide feedback from class-server to class-client.
C# delegate is smarter then “standard” callback because it allows defining a strict list of parameters which are passed from class-server to class-client.
In our sample, class-server has the name
DataHolder. It holds a collection of data items. Data item is defined in class
DataItem. Any data item has two attributes:
DataHolder contains a method which allows to search through the data collection in order to find data items which meet a search condition. This method contains two parameters. The first parameter defines search criteria. The second parameter defines a method to call when search criteria is reached.
It is very important to understand that class-server loops all data collection from the start to the end. In case if data item meets the search condition, class-server calls a method defined in class-client. The amount of back calls from class-server to class-client is the same as amount of data items in collection meeting the search criteria.
MainClass is a class-client. It creates instance of
DataHolder class (
lst) and instance of delegate with type “
CallBack”. The delegate instance (
procedure01) contains information: what user-defined method (
PrintSearchResult) class-server has to call in class-client, and what parameters class-server has to pass to this user-defined method. The list of parameters which are passed to user-defined method of class-client is defined in the delegate declaration. Of course, the list of parameters in user-defined method must exactly meet the list of parameters in delegate declaration.
This is the main idea of C# delegate. I recommend to pass the sample project in debugger in order to get step-by-step review of execution.