Events (C# vs. Java)

This topic compares event handling in C# and Java.

An event is a way for a class to notify the users of an object when something of interest happens to this object. This notification is called raising an event. The object that raises an event is referred to as the publisher or sender of the event. For example, a window object typically raises an event when a mouse click occurs within its region. Another class can listen (or subscribe) to the event, and execute its own custom code when the event is raised. In other words, the publisher controls when the event is raised, and the subscriber or listener controls what action it will take in response to the event. The action is defined in a method called an event handler.

In most event-driven programming, it is common to write event handlers, and less common to write classes that generate or raise the events. This topic therefore focuses on event handling.

In Java, when you want to receive an event from another class, you typically create a class that implements one or more of the listener interfaces, such as ActionListener and MouseListener. You then register your listener with the event publisher object, and that object will call a specific predefined method in your listener when the event occurs.

In C#, events are members of the publisher class. To subscribe to an event, you just add your event handler method to the event, as shown in the following example:

window.ClickedEvent += MyEventHandler;

In the previous example, MyEventHandler is a method that is defined in the subscriber class, and ClickedEvent is an event that is defined in the window class. When the window class raises ClickedEvent, it calls the MyEventHandler method in the subscriber class. Type safety is enforced behind the scenes by delegates. The signature of MyEventHandler must match the signature that is specified by the delegate type of the ClickedEvent. But, unlike in Java, there is no restriction on the name of the event handler method. For more information about delegates, see Delegates (C# Programming Guide). For more information about events, see Events (C# Programming Guide).

Java provides alternative ways to create event handlers, such as anonymous classes. C# 3.0 has anonymous types, but they are not used for event handling. However, in C# 2.0, you can use an anonymous method to create an inline event handler:

button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };

The C# compiler converts this code into a delegate at compile time. In C# 3.0, you can also use lambda expressions to create both delegates and expression trees, which are object representations of expressions. For more information about anonymous methods and lambda expressions, see Anonymous Functions (C# Programming Guide).

Example

Description

The following example defines an event that has three methods associated with it. When the event is triggered, the methods are executed. One method is then removed from the event and the event is triggered again.

Code

// Declare the delegate handler for the event. The delegate
// defines a signature that returns void and has no parameters.
public delegate void MyEventHandler();

class TestEvent
{
    // Declare the event of type MyEventHandler. Event handlers
    // for TriggerIt must have the same signature as MyEventHandler.
    public event MyEventHandler TriggerIt;

    // Declare a method that triggers the event:
    public void Trigger()
    {
        TriggerIt();
    }
    // Declare the methods that will be associated with the TriggerIt event.
    public void MyMethod1()
    {
        System.Console.WriteLine("Hello!");
    }
    public void MyMethod2()
    {
        System.Console.WriteLine("Hello again!");
    }
    public void MyMethod3()
    {
        System.Console.WriteLine("Goodbye!");
    }

    static void Main()
    {
        // Create an instance of the TestEvent class.
        TestEvent myEvent = new TestEvent();

        // Subscribe to the event by associating the handlers with the event:
        myEvent.TriggerIt += new MyEventHandler(myEvent.MyMethod1);
        myEvent.TriggerIt += new MyEventHandler(myEvent.MyMethod2);
        myEvent.TriggerIt += new MyEventHandler(myEvent.MyMethod3);
        // Trigger the event:
        myEvent.Trigger();

        // Unsuscribe from the event by removing the handler from the event:
        myEvent.TriggerIt -= new MyEventHandler(myEvent.MyMethod2);
        System.Console.WriteLine("\"Hello again!\" unsubscribed from the event."); 

        // Trigger the new event:
        myEvent.Trigger();
    }
}

Output

Hello!
Hello again!
Goodbye!
"Hello again!" unsubscribed from the event.
Hello!
Goodbye!

See Also

Concepts

C# Programming Guide

Reference

event (C# Reference)

delegate (C# Reference)

Other Resources

C# for Java Developers

Change History

Date

History

Reason

September 2008

Clarified and updated text.

Customer feedback.