DEV Community

Cover image for C# : EventHandler
Felipe Matheus de Souza Santos
Felipe Matheus de Souza Santos

Posted on • Updated on

C# : EventHandler

Why am I posting this?

When learning C# I think Event Handler is one of the first subjects that beginners struggles with, it is like that first tough boss of a RPG video game, this is totally understandable because for a beginner perspective Event Handler is probably the first contact with levels of abstractions that needs to be comprehended.

While Microsoft as usual provides of excellent documentation, still the technical level of detail of their writings might not facilitate much depending on how much you already know, so I hope to share a more simplified vision straight to the point to make you able to understand the fundamentals.

Learning method

I will not focus on code syntax here, because I believe this is one of the biggest reasons why the majority of people struggles with when they try to learn a programming language, they are too concerned with syntax instead of concentrating on what the code is really doing!
I believe you can easily translate the concepts described here into C# code as long as you understand the purpose behind it.
I'm not saying you should not practice coding, on the contrary I hope you practice it a lot! But before you jump into it, understanding what your code should do and most importantly how it does it, is essential!

What is an Event?

Please note I'm now describing Event and not Event Handler

An event is a message sent by an object to signal the occurrence of an action. The object that raises the event is called the event sender.

For example, think about a button called click me as the event sender for the event click.

The event sender (button) doesn't know the objects or methods that will receive the event it raises (click).

So suppose that, by clicking this button in a web page, the background color of the page changes, also all the text color contained in the page changes!

The button is just the button, it doesn't know about the page background or its text, it is there only to send an event (click) to the program (the page) that is going to be listened by other components (background and text).

The question at this point is "But how exactly background and text can "hear" the event and respond to it?" and to answer that we need to learn what is a Delegate

What is a Delegate

The simplest way to think about a Delegate, is to think about storing an object into a variable, your variable becomes a reference to that object in your memory.

So, Delegates are specifically methods references, really, consider the below code:

// This code will return true
string someString = "Hi";
var refMethod = someString.Contains("H");
Console.WriteLine(refMethod);
Enter fullscreen mode Exit fullscreen mode

With the above example, we're not defining a Delegate, but I'm just trying to demystify for you what a Delegate really is!

So how exactly a Delegate is different from the above example? The detail is that a Delegate works as a pointer living inside of a given object to other methods (from other objects/classes), and for this to work the method it points to must fulfill a method signature. A method signature is composed by:

  • the data type the method returns
  • the parameters types it takes and its order

The method signature fulfillment between a Delegate and the methods it references is called the Delegate contract

Wrapping it up

Okay, so we've started talking about Events, then we've talked about Delegates, so what is an Event Handler?

In few words, an Event Handler is an execution chain of Delegates!

So, remember our button? Now you should know that the button contains an Event Handler which defines a Delegate contract, that will serve to further register Delegates that are pointers to other object methods that fulfills the contract.

Translating it to code!

If you have read until here, and you did not know anything about how Event Handlers truly works on C# I really hope the code below now makes much more sense to you than it would before it!

Note that I'm not concerned with the actual implementation of a real web page behavior, instead we're just writing to the console for example simplicity.

Class button

using System;

namespace Practice
{
    public class Button
    {
        // Defines an Event Handler that returns no object data
        public EventHandler Click;

        // Defines a method that raises the event handler to be listened by other object methods
        protected virtual void OnButtonClicked(EventArgs e)
        {
            Click?.Invoke(this, e);
        }

        // Defines a method that calls the method that raises the EventHandler
        public void OnClick()
        {
            Console.WriteLine("Click event sent");
            OnButtonClicked(null);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Class WebPageBackground

    public class WebPageBackground
    {
        // Defines a method that fulfills the EventHandler Delegate contract
        public void OnButtonClicked(object source, EventArgs e)
        {
            Console.WriteLine("Change background color");
        }
    }
Enter fullscreen mode Exit fullscreen mode

Class WebPageText

    public class WebPageText
    {
        // Defines a method that fulfills the EventHandler Delegate contract
        public void OnButtonClicked(object source, EventArgs e)
        {
            Console.WriteLine("Change text color");
        }
    }
Enter fullscreen mode Exit fullscreen mode

Class Program

    class Program
    /*
     Outputs: 
         Click event sent
         Change background color
         Change text color
    */
    {
        static void Main(string[] args)
        {
            // Create new instances of each class
            var button = new Button();
            var background = new WebPageBackground();
            var text = new WebPageText();

            // Register Delegates in the Click EventHandler contained in the button object
            button.Click = background.OnButtonClicked;
            button.Click += text.OnButtonClicked;

            // Run
            button.OnClick();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

As I said earlier in this post, consider this as a more descriptive and detailed entry point of the subject, you should now at least know exactly about what the code is doing! and taking from here I hope you'll learn more in deep about Event Handlers and Delegates in C# as a piece of cake! :)

Feedback

This was my very first post here on DEV community (hooray), and I would love to hear from you! my biggest compensation for the time I spent here is to know if I truly could help someone out there, and also to learn from your feedback!

Discussion (0)