System ProgrammingLearn About Events in C# Programming

Learn About Events in C# Programming

c#-20

We’ve talked about delegates before, and how they can be used as pointers to functions. Delegates are the cornerstone of what’s called events, which represent one of the basic pillars of Windows GUI programming.

In all the previous codes we’ve explored, you created “Console Applications”. These are programs that get executed on the Windows command line shell in a “procedural” manner. That is, the program executes a statement, then either waits for the user input or executes the following statement depending on the code written. But modern programs do not work this way. In a typical application, you open a window with menus and buttons and, possibly, some components like a scroll bar, a timer, a calendar, etc. Those components are waiting for user interaction, which cannot be anticipated. For example, a user may click on button A, then ignore button B and move the scroll bar to see more text before he/she presses button C. A procedural program cannot work this way because, as mentioned, it works step by step, one statement after the other. The solution is to use Events.

An event is just a class member, like fields and methods, but it gets invoked (fired) as soon as a pre-defined action happens; for example a mouse click. The class where the event is defined is sometimes called the publisher, while the class(es) that register to this event, and provides code (event handler) that gets executed the moment the event action happens is called a subscriber class. A publisher class uses a delegate to provide event handling code.

Let’s modify our Car class to reflect the use of events: you want the car to move but also want to monitor its speed at the same time. We are going to make a for loop that will increment the speed integer variable by 1 until it reaches 20, we make the application sleep for one second per iteration to be able to view the progress on the screen. Once speed exceeds 10, an event will be fired. It is the responsibility of the subscriber code (defined in the Main() method) to provide code that will handle this event. In our case, write a warning message to the screen:

class Car : Vehicle
    {

        public delegate void SpeedExceededHandler();
        public event SpeedExceededHandler SpeedExceeded;

        public int speed = 0;

        public void drive()
        {
            for (int i = 0; i < 20; i++)
            {
                if (i >= 10)
                    SpeedExceeded();
                speed += i;
                Console.WriteLine("Current speed is " + i);
                System.Threading.Thread.Sleep(1000);
            }
        }
    }

Notice how the event was created: we first defined a delegate to which the handler method of the subscriber code will point to. The subscriber method must match the signature of this delegate method. In our case, its signature is just a void method that takes no parameters. Then we create the event itself. The event has the delegate we’ve just created as its type and it can have any descriptive name.

Learn the Basics of C Programming Language

The rest of the code is simple, a method drive containing the loop that we’ve just discusses. But we add a condition checking at each iteration whether or not the speed has exceeded the predefined limit (10). If this happens, the code fires the event, just the same way any method is called. Now let’s have a look at the code that will subscribe to this event:

    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car();
            myCar.SpeedExceeded += myCar_CarMoved; 
            myCar.drive();
            
        }

        static void myCar_CarMoved()
        {
            Console.WriteLine("Car has exceeded speed limit");
        }
    }

Now, the only thing new here is the += sign. This is an overloaded operator that is used to subscribe to the event. Subscription is made by referencing the event name (SpeedExceeded) += a method name that has the same signature as the delegate. We created a myCar_CarMoved() method underneath it to represent the event handler. Notice that you must subscribe to the event before trying to use it. Failing to do so will result in a “null reference” error that is very hard to debug as it will not point you to the line number where the exception happened.

Now let’s run the code:
1

As you can see the loop is incrementing the current speed of the car till it reaches 10. After which the event fires and the code handler starts printing warnings to the screen till the 20 iterations are over.

In a console application, events may not be that important. But in a GUI application, all code is event based. For example you subscribe to a button_click event that will get fired as soon as .net receives a user click on the button. Your code handler should provide the program with instructions to carry out in response to this event, say a welcome message box.

Conclusion
In this article, we have delved into Events, the cornerstone of GUI programming. You saw what they are, how they are related to delegates, how they can be defined, published, and subscribed to.
I hope you enjoyed reading this article.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -