Delegates And Events–Part 1 of 3

19. November 2020 09:45 by Parakh in Visual C#  //  Tags: , ,   //   Comments
This post attempts at explaning the concept of delegates and events in C# as it relates to real life, in as simple a manner as possible.

In my experience, if there’s one topic in C# that baffles the programmers the most, it is the topic of events and delegates. And the root of the state of confusion is not the lack of attempt on the programmer’s part, but the way the books on programming languages explain the concept – in a dry academic sense, devoid of any relatability to real life.

This blog post is my attempt to explain the concept of events and delegates in an easy way.

Events in real life are occurrences where something of importance happened to an entity. Let me elaborate on that. Consider a normal human being. Events in the life of a normal human being would be:
1. Birth
2. First day of school
3. Graduation from school
4. First day of college
5. Graduation from college
6. First pay-check
7. Getting married
8. First child
…and so on. The aforementioned occurrences would normally be considered important, hence endowed with a special term, events.

Whenever an event occurs, there’s something done. Birth of a child is celebrated, graduation from school is celebrated with a farewell party, marriages are celebrated with near and dear ones, etc.

This is what is the inspiration for the abstraction, aptly called events in modern object-oriented programming languages. Events are important occurrences in the life-span of an entity. An entity can be a button in a Windows Form, a dropdown on a web page, or some kind of a custom activity in a user-defined object like a domain class. Correspondingly, the event would be pressing a button, changing the selected element in a dropdown or value of a property in a domain class.

Whenever some event occurs or gets fired, something is done. That something is done in some defined code, called the event handler. An event handler is essentially a method, with details of what needs to be done when the event is fired.

Now that we have understood the concept of events and event handlers, let’s understand the concept of delegates. Delegates are like the consciousness that pushes us to do something when an event occurs. Essentially, a delegate is the glue that ties an event and an event handler together.

To summarise:
When something of importance happens -> Event
What we do in case of an event -> Event Handler
The glue connecting the event and event handler –> Delegate

I hope that this post was able to sow the idea of events and delegates your mind in a non-technical and relatable way. In future posts, I will shed more light on the topic.

blog comments powered by Disqus

Month List

ParakhSinghal@Twitter.com

Note: For Customization and Configuration, CheckOut Recent Tweets Documentation