Basic Events in C#

Events in C#

The .NET framework is based upon the concept of events, like many other technologies. An event is simply a way of letting the programmer know that something has happened, and allowing them to respond to that event in whichever way they require.

In Programming terms Events are objects which contain a list of methods (“handlers”) to be executed on the current thread. (Be aware that even if event handlers are registered and declared on another thread they are run on the thread that the event is called on.) These are executed when the object raising the event deems it necessary.

For example, the object Timer has the event “Tick”, which is called when the Timer updates itself. The programmer can register a handler (method) with the event, which will be executed when this happens.

Subscribing to (or registering with) current events

In C# we add a handler to an event using the += operator. The object to be added is a delegate, which is in essence a method encapsulated in a variable. It is this method that will be executed. The delegate determines the arguments and return type of the method.

Delegates are often declared as void and take the args  object sender, EventArgs e .

In WPF it is not uncommon to see  object sender, System.RoutedEventArgs e, as events are run slightly differently.

IDEs like Visual Studio (Express) can automatically determine which delegate is required, and allow you to generate a method stub by pressing Tab after adding the += operator after an event.

We subscribe to events in this form:

Object.Event += new System.EventHandler(Object_Event)

private void Object_Event (object sender, EventArgs e)

{

//Code to be executed upon event being called

}

Events differ in their requirements in terms of delegates. This example event simply used the default System.EventHandler; other events declare their own delegates to be used. Check with your IDE to determine the correct one to use.

Similarly each event can have its own EventArgs inheritor, such as Timers.ElapsedEventArgs,  which the delegate passes as an argument, so when declaring the method that is executed when the event is called, ensure that the appropriate args are declared also.

About theadminjr

Programmer, 3D Modeller, Video Editor Main Languages: Python, C#, VB
This entry was posted in C#, Fundamentals, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s