Home |  JournalSeek |  SoftwareSeek |  GenomeSeek |  Expression |  Developer |  TakeOnIt
Return to Genamics Home

5. Events

C# provides direct support for events. Although event handling has been a fundamental part of programming since programming began, there has been surprisingly little effort made by most languages to formalize this concept. If you look at how today's mainstream frameworks handle events, we've got examples like Delphi's function pointers (called closures), Java's inner class adaptors, and of course, the Windows API's message system. C# uses delegates along with the event keyword to provide a very clean solution to event handling. I thought the best way to illustrate this was to give an example showing the whole process of declaring, firing, and handling an event:

// The Delegate declaration which defines the signature of methods which can be invoked
public delegate void ScoreChangeEventHandler (int newScore, ref bool cancel);

// Class which makes the event
public class Game {
    // Note the use of the event keyword
    public event ScoreChangeEventHandler ScoreChange;

    int score;

	// Score Property
    public int Score {
        get {
            return score;
        set {
            if (score != value) {
                bool cancel = false;
                ScoreChange (value, ref cancel);
                if (! cancel)
                    score = value;

// Class which handles the event
public class Referee
    public Referee (Game game) {
        // Monitor when a score changes in the game
        game.ScoreChange += new ScoreChangeEventHandler (game_ScoreChange);

    // Notice how this method signature matches the ScoreChangeEventHandler's signature
    private void game_ScoreChange (int newScore, ref bool cancel) {
        if (newScore < 100)
            System.Console.WriteLine ("Good Score");
        else {
            cancel = true;
            System.Console.WriteLine ("No Score can be that high!");

// Class to test it all
public class GameTest
    public static void Main () {
        Game game = new Game ();
        Referee referee = new Referee (game);
        game.Score = 70;
        game.Score = 110;

In the GameTest we make a game, make a referee who monitors the game, then change the game's score to see what the referee does in response to this. With this system, the Game has no knowledge of the Referee at all, and simply lets any class listen and act on changes made to its score. The event keyword hides all the delegate's methods apart from += and -= to classes other than the class it is declared in. These operators allow you to add (and remove) as many event handlers as you want to the event.

You will probably first encounter this system in GUI frameworks, where the Game would be analogous to UI widgets which fire events according to user input, and the referee would be analogous to a form, which would process the events.

Delegates were first introduced in Microsoft's Visual J++ also designed by Anders Hejlsberg, and were a cause of much technical and legal dispute between Sun and Microsoft. James Gosling, the man who designed Java made a condescending though humorous comment about Anders Hejlsberg, saying his attachment to Delphi made him "Mr. Method Pointers". After examining the arguments against delegates made by Sun, I believe it would be fair to call Gosling "Mr. Everything's-a-Class". In the last few years of programming "make abstractions which try to model reality well" has been replaced by many people with "Reality is object-oriented, so we should model it with object oriented abstractions".

Sun's and Microsoft's arguments for and against delegates can be found at:

Previous     Next

C# 3.0 in a Nutshell (April 2007) - by Joseph Albahari and Ben Albahari.

Add To Favorites
Email This Page

Side Panel
Privacy Policy About Us Contact Us