TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Event Example: EventHandler

This C# example program uses an event type with EventHandler. Events can have many EventHandlers.

Event. An event can have many handlers.

With the event handler syntax, we create a notification system. We attach additional methods without changing other parts of the code. This makes programs easier to maintain.

Methods

Example. First, this example shows the event keyword. It creates an original event. The .NET Framework has many existing events: these are covered elsewhere. The delegate keyword is used to specify the EventHandler type.

Next: The event keyword is used to create an instance of an event that can store methods in its invocation list.

Based on:

.NET 4.5

C# program that uses event handler

using System;

public delegate void EventHandler();

class Program
{
    public static event EventHandler _show;

    static void Main()
    {
	// Add event handlers to Show event.
	_show += new EventHandler(Dog);
	_show += new EventHandler(Cat);
	_show += new EventHandler(Mouse);
	_show += new EventHandler(Mouse);

	// Invoke the event.
	_show.Invoke();
    }

    static void Cat()
    {
	Console.WriteLine("Cat");
    }

    static void Dog()
    {
	Console.WriteLine("Dog");
    }

    static void Mouse()
    {
	Console.WriteLine("Mouse");
    }
}

Output

Dog
Cat
Mouse
Mouse

Control flow begins in the Main entry point. The _show event has four method instances added to its invocation list with the plus "+=" operator. This has no relation to the arithmetic addition operator.

Next: In the invocation list of the _show event, we add four events: Dog, Cat and two instances of Mouse.

Finally: When the Invoke method is called, each of those method instances are called. The strings are printed to the console.

Console.WriteLine

In this program, we use the static modifier on the event. This is not important. The example was designed this way to enable the event to be accessed directly in the static Main method: for simplicity.

Often: In program design, avoiding static instances is worthwhile. It can lead to many dependencies and excess complexity.

Static

Discussion. Events let you add methods to be triggered upon an external event. In your program design, you might add new event handlers dynamically for a specific action. Then at some point the Invoke method could be called.

Events reduce excessive changes. At the part of the code where you call Invoke to signify the event, you would not need to know all the different handlers that were added. This reduces the number of changes to the code.

Tip: The event handler notification system provides a way to isolate different parts of your program from excessive changes.

Uses. Events are used in many objects in the .NET Framework. The Windows Forms framework uses events for many controls. These events allow you to instantly act upon button clicks and key presses.

Windows Forms

Note: With threading, we use events on the BackgroundWorker type. We can monitor file system changes with FileSystemWatcher.

BackgroundWorkerFileSystemWatcher

Research. Notifications are important. A class can provide notifications with an event. And then all other parts of the program can handle these events with event handlers. This is explained in the C# specification.

An event is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers.

The C# Programming Language

Specialized languages. With events we can create a specialized language. A language is described with three principles. The first principle is use of primitive operations. The second is a way to combine elements. And the third is an ability to specify methods.

A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize our ideas about processes.

SICP

With events, the methods added to the event are the primitive functions. By adding event handler instances to an event, we achieve a means of combination. And the methods serve as a means of abstraction for a real-world model.

Caution: You can create an event with nearly any code construct. This material has little relation to the "event" C# keyword.

Summary. Typically, events are used on the built-in types developed for the .NET Framework itself. But for certain programs that need to attach many behaviors to different actions, custom events can provide an additional level of indirection.

Thus: With events we separate something that happens from the behaviors we want to occur. And this leads to higher-quality programs.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf