Skip Navigation Links

 CodeMatrixThe ultimate site for .NET programmers

Skip Navigation Links.    

Events in C#

An event is a way for a class to provide notifications when something of interest happens. For example, a class that encapsulates a user interface control might define an event to occur when the user clicks on the control.

Events use delegates to provide type-safe encapsulation of the methods that will be called when triggered.

In the following example, the class TestButton contains the event OnClick. Classes that derive from TestButton can choose to respond to the OnClick event, and also define the methods that are to be called in order to handle the event. Multiple handlers, in the form of delegates and anonymous methods, can be specified.

using System;
using System.Collections.Generic;
using System.Text;

namespace Events
{
    // Declare the handler delegate for the event
    public delegate void SampleEventHandler();

    class TestButton
    {
        // OnClick is an event, implemented by a delegate SampleEventHandler.
        public event SampleEventHandler OnClick;

        // A method that triggers the event.
        public void Click()
        {
            OnClick();
        }

        // A method that will be triggered by the OnClick event.
        public void TestHandler()
        {
            System.Console.WriteLine("Hello, World!");
        }
    }

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

            // Specify the method that will be triggered by the OnClick event.
            mb.OnClick += new SampleEventHandler(mb.TestHandler);

            // Specify an additional anonymous method.
            mb.OnClick += delegate { System.Console.WriteLine("Hello, There!"); };

            // Trigger the event
            mb.Click();
        }
    }
}
The output of example is as follows:
Hello, World!
Hello, There!

Copyright © 2008 www.codematrix.net, All Rights Reserved. Disclaimer