Click here to Skip to main content
15,886,578 members
Articles / Programming Languages / C#
Article

The Simplest C# Events Example Imaginable

Rate me:
Please Sign up or sign in to vote.
4.11/5 (116 votes)
5 Sep 20052 min read 827.7K   143   62
A simple metronome example where a class creates events and another receives them.

Introduction

Most examples of events and delegates in C# are more complicated and intimidating than a person new to both C# and OOP would like (VBA made it just too easy on us). While I will not explain the code, it is simple enough that what code to replace in a copy-paste is clear. I have created what I think may be one of the simplest examples of Event Handling in C#. A Metronome class creates events at a tick of 3 seconds, and a Listener class hears the metronome ticks and prints "HEARD IT" to the console every time it receives an event. This should give the novice programmer a clear idea what is necessary to generate and pass events. Plop the following code right into a class file in a blank C# project.

C#
using System;
namespace wildert
{
    public class Metronome
    {
        public event TickHandler Tick;
        public EventArgs e = null;
        public delegate void TickHandler(Metronome m, EventArgs e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    Tick(this, e);
                }
            }
        }
    }
        public class Listener
        {
            public void Subscribe(Metronome m)
            {
                m.Tick += new Metronome.TickHandler(HeardIt);
            }
            private void HeardIt(Metronome m, EventArgs e)
            {
                System.Console.WriteLine("HEARD IT");
            }

        }
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            Listener l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }
}

A slightly more complicated example is if the event has information passed with it, such as mouse coordinates for a mouse event or which key is pressed for a keypress event. To do this you need to create an appropriate class derived from the EventArgs class and then set an instance of it before raising the event. See below:

C#
using System;
namespace wildert
{
    
    public class TimeOfTick : EventArgs
    {
        private DateTime TimeNow;
        public DateTime Time
        {
            set
            {
                TimeNow = value;
            }
            get
            {
                return this.TimeNow;
            }
        }
    }
    public class Metronome
    {
        public event TickHandler Tick;
        public delegate void TickHandler(Metronome m, TimeOfTick e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    TimeOfTick TOT = new TimeOfTick();
                    TOT.Time = DateTime.Now;
                    Tick(this, TOT);
                }
            }
        }
    }
        public class Listener
        {
            public void Subscribe(Metronome m)
            {
                m.Tick += new Metronome.TickHandler(HeardIt);
            }
            private void HeardIt(Metronome m, TimeOfTick e)
            {
                System.Console.WriteLine("HEARD IT AT {0}",e.Time);
            }

        }
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            Listener l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }
}

When you add a button to a form in C# and double click on the button in the form designer, you are taken to a method equivalent to "Heardit", but it will be appropriately named something like Button1_Click. Button1 is set up with a standard event handler (System.EventHandler, which is discussed below in the comments) and its own events (Click, MouseMove, etc). If you dig into the Form1.Designer.cs code, you will find the last necessary bit of code.

this.button1.click += new System.EventHandler(this.button1_Click);

What the auto-designer code did for you was add a new class Button1 with Button events and uses System.EventHandler, and then had Form1 subscribe to its events and create a Button1_Click method in Form1. Awful English, I'm an engineer.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGreat Article Buddy....... Pin
PratapDessai17-Feb-10 19:33
PratapDessai17-Feb-10 19:33 
GeneralRe: Great Article Buddy....... Pin
Matic Marko6-Apr-10 21:22
Matic Marko6-Apr-10 21:22 
QuestionIs there code for a complete project? Pin
John Chaffins16-Dec-09 10:32
John Chaffins16-Dec-09 10:32 
AnswerRe: Is there code for a complete project? Pin
Todd Wilder16-Dec-09 11:07
Todd Wilder16-Dec-09 11:07 
GeneralRe: Is there code for a complete project? Pin
John Chaffins22-Dec-09 10:42
John Chaffins22-Dec-09 10:42 
GeneralPublish/Subscribe across user controls Pin
Kjartan933-Sep-09 7:38
Kjartan933-Sep-09 7:38 
GeneralRe: Publish/Subscribe across user controls Pin
Todd Wilder3-Sep-09 8:45
Todd Wilder3-Sep-09 8:45 
QuestionWhat is the reason to check if the event is null? Pin
Maxi Ng @ TW21-Jul-09 21:25
Maxi Ng @ TW21-Jul-09 21:25 
if (Tick != null)
{
Tick(this, e);
}

What will go wrong if I just raise it without checking?
Tick(this, e);

Let's create a game.
Visit my technical note blog http://maxi326.wordpress.com

AnswerRe: What is the reason to check if the event is null? Pin
Todd Wilder22-Jul-09 12:38
Todd Wilder22-Jul-09 12:38 
GeneralThanks! Pin
Gordopolis3-Sep-07 5:58
Gordopolis3-Sep-07 5:58 
GeneralAn excellent understandable article! Pin
thunderbirdje23-Aug-06 12:39
thunderbirdje23-Aug-06 12:39 
GeneralPerfect Pin
snorkie9-Jun-06 10:33
professionalsnorkie9-Jun-06 10:33 
QuestionSimplified? Pin
Peter Ritchie13-Sep-05 3:12
Peter Ritchie13-Sep-05 3:12 
GeneralSimplified Even Further... Pin
Timpie9-Sep-05 12:30
sussTimpie9-Sep-05 12:30 
GeneralMore so... Pin
Pinhead_Me7-Aug-06 7:07
Pinhead_Me7-Aug-06 7:07 
GeneralRe: More so... Pin
Todd Wilder7-Aug-06 12:22
Todd Wilder7-Aug-06 12:22 
GeneralGood job - very simple Pin
Susan Hernandez7-Sep-05 6:10
Susan Hernandez7-Sep-05 6:10 
GeneralThanks! Pin
verger6-Sep-05 18:29
verger6-Sep-05 18:29 
GeneralDetail of System.Eventhandler Pin
Todd Wilder6-Sep-05 9:17
Todd Wilder6-Sep-05 9:17 
GeneralRe: Detail of System.Eventhandler Pin
gleizerowicz9-Sep-05 9:50
gleizerowicz9-Sep-05 9:50 
GeneralSimplified Even Further... Pin
joriolt6-Sep-05 9:05
joriolt6-Sep-05 9:05 
Generalsimple yet good enough Pin
Huisheng Chen5-Sep-05 17:22
Huisheng Chen5-Sep-05 17:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.