Events & Delegates In C# - The Concept

Posted by Ahmed Tarek Hasan on 9/07/2012 04:55:00 PM with 2 comments
I encourage you to read Delegates In C# - The Definition article first to understand the main definition of delegates in C#.


The main essence of object oriented programming (OOP) is that it simulates the life we live. Before OOP, the programing approaches were oriented to getting the job done by writing some code to apply some logic. But, OOP was the start point to try to introduce a new approach which is more related and similar to the way we, human beings, live, perform and communicate. That's why when I try to understand a new concept in OOP I first try to find the resemblance which may occur between the concept and the real life I live. So, lets try to find this resemblance in the case we have in our hands, "Events & Delegates in C#".

To fully understand the main concept and behavior of events and delegates in C#, we need to imagine the whole thing as if it is a way by which two or more parties communicate to share info and take actions depending on these info. To do so, let's clear our mind and leave the IT talking aside for a short time.

Imaging that we have a "Teacher" and a "Student". The teacher has a Q & A game to play with the student. The teacher should ask a question and if the student knows the answer he should provide the answer. Then, the teacher should check if the answer is right or wrong and accordingly a score will be calculated.

So, for the game to succeed, both parties, teacher and student, should know the rules to be able to follow the same rules and be on the same page and at last the game should begin. So, for the whole thing to start, there should be 2 stages to follow.

The first stage is "The agreement":
In this stage the teacher tells the student the rules and the student tells the teacher how he will respond and at last they shake hands. So the conversation should be like:
Teacher: When I have a question, I will raise my hand and say; "I have a question".
Student: Ok, and if I want to play, I will ask you for the question and tell you how I will provide the answer (written on paper, by mouth, by mail, .....).
Teacher: Ok, so in this case, I will give you the question and i will get the answer from you by the way you told me about. Then, I will check your answer and update the score.
Student: Ok, that's fine.
Teacher: Ok, then let's start playing.

So, to recap what happened in this stage, we will find that the conversation here is more detailed than the conversations in our real life and that is because eventually we are talking about a development technique and approach which needs both parties in any conversation to be in full control of the info flow leaving nothing to opportunities. So, we already know that this conversation in real life could take only a 2 lines dialogue but here it needs to be more detailed for both parties to know what they will really face in the IT world :)

So, for this stage to complete, we needed to have some main entities:
  1. First party, the conversation initiator .......... teacher
  2. Second party, the responder .......... student
  3. The action by which the initiator will initiate .......... saying "I have a question"
  4. The info provided by the initiator ........... question
  5. The info provided by the responder ........... answer
  6. The way by which the responder will provide the response ........ written on paper, by mouth...
  7. The way by which the initiator will use the response .......... calculation of score

The second stage is "Starting conversation":
At this stage, the game starts as follows:
Teacher: I have a question
Student: Ok, I want to play, please tell me the question and I will write the answer on paper and hand it to you.
Teacher: Ok, the question is "What is your name?". I am waiting for the paper on which you will write your answer. Then i will check the answer and update the score.
Student: Ok, here is the paper including my answer.
Teacher: After checking your answer, I am now updating the score.


Now, lets return to the IT talking.


How can we map this to Events & Delegates in C#?
Now, I think we have an image of what a conversation in C# would look like between two parties. Now let's see how each entity of the conversation (the 7 entities above) will look like into C#.
  1. First party, the conversation initiator .......... teacher ....... The class (A) which will raise an event when certain action takes place
  2. Second party, the responder .......... student .......... Every other class (B, C, ...) wants to be notified when the class A raises its flag
  3. The action by which the initiator will initiate .......... saying "I have a question" ........ The event which the class A will raise
  4. The info provided by the initiator ........... question .......... The info which the class A will provide while raising its event to be used by any listening classes (B, C, ....)
  5. The info provided by the responder ........... answer ......... The info which the class B will provide after processing the info provided by class A
  6. The way by which the responder will provide the response ........ written on paper, by mouth..... The delegate which class B will provide to class A to be executed by class A when the event is raised
  7. The way by which the initiator will use the response .......... calculation of score ......... The logic of class A which will continue after executing the delegate provided by class B

Can you elaborate more?
To recap, what really happens is:

The agreement:
  1. A delegate is defined in scope recognized (referenced) by both Class A and Class B
  2. This delegate defines the header (return type and input parameters) of the method which will be provided by Class B to Class A to be executed by Class A when it raises its event
  3. An event is defined inside Class A to be raised at certain point by the logic of Class A
  4. This event should be mapped to the delegate we already defined before so that it is known that the method that should be provided by Class B should have the header defined by the delegate
  5. A class inheriting from the .Net class "EventArgs" should be defined in scope recognized (referenced) by both Class A and Class B
  6. This class should include some properties encapsulating the info which Class A should provide to Class B while raising the event to be used by Class B inside its delegate if needed
  7. Inside the logic of Class A, the event should be raised when needed
  8. At the line of code where Class A raises the event, Class A can receive the return of the delegate to be used in the rest of the logic if needed
  9. This return value is determined inside the logic of the delegate which is provided by Class B
Starting conversation:
  1. In the main program which can see both Class A and Class B, the events of instances of Class A should be binded to the delegate provided by Class B
  2. Now, whenever every instance of Class A raises its event, the delegate will be executed and a return value will be provided so that the instance of Class A can use this return value in the rest of its logic
 Some notes:
  1. Class A and Class B may not know anything about each other
  2. Class A doesn't know if any other class is interested in its event and the info it provides or not
  3. In the line of code where Class A raises its event, it checks if any class is interested in its event and info or not. If any class is interested, then Class A will wait till the delegate provided by this interested class is executed. Then Class A will receive the return of the delegate and then Class A will complete its logic
  4. The delegate definition which defines the header (return type and input parameters) of the method to be executed by Class A when it raises its event may have no return type, in other words, it may have "void" as its return type. This means that Class A doesn't need any info or feedback from the interested classes

Have we seen any of this logic before in .Net built-in functionality/module?
Yes for sure. you have already seen this while using the windows forms applications controls like the "Button" control. When you add a button to the form and go to the code behind, you will find that the button will have a member called "Click" with the yellow bolt icon beside it in the intellisense menu. This member is the event defined inside the button control/class. Also, you can bind an action to this event using the "+=" operator so that you can fire a certain action/code/logic when the button is clicked at runtime. When you write the "+=" operator and follow it by two tabs, you will find that a line is automatically written after the "+=" operator. This line is "new EventHandler(this.buttonName_Click);". Also, a new empty method is created having the header "void buttonName_Click(Object sender, EventArgs e)".
  • For the "new EventHandler", "EventHandler" is the delegate used to provide the header for the method to be called by the button when it is clicked
  • For "this.buttonName_Click", "buttonName_Click" is the method (which follows the header defined by the delegate "EventHandler") used to provide the implementation/code/logic to be executed when button is clicked
  • For "EventArgs e", "EventArgs" is the class defining the properties encapsulating the info provided by the button itself when it is clicked
  • For the code that will be written inside the empty method, this is the code which will be executed by the button when it is clicked at runtime

Can we see a practical example on how to use Events & Delegates in C#?
Yes, I will provide an example on using Events & Delegates in windows forms applications controls. I will update this article with the link once the new article is ready.
I already created an article on how to use Events & Delegates in Win Forms Controls. You can find it here



At last, I wish this article helped you a bit to understand the whole picture of "Events & Delegates in C#".

Good Luck :)


Categories: , ,