Monday, January 28, 2008

C# Events

using System;
using System.Windows.Forms;
namespace EventsMadeSimple
    public partial class Form1 : Form
        SimpleClass SimpleObject = new SimpleClass(); // create a new SimpleClass object
        public Form1() // Form1 constructor
            Load += new EventHandler(Form1_Load); // add Form1's Load event handler
            // add our object's event handler
            SimpleObject.SimpleEvent += new OnSimpleEvent(SimpleEventOccurred);
        void Form1_Load(object sender, EventArgs e)
            SimpleObject.SimpleMethod(); // call the SimpleObject's method
        private void SimpleEventOccurred() // method is called when the event is raised
            listBox1.Items.Add("SimpleEvent was fired at " + DateTime.Now.ToString());
    public delegate void OnSimpleEvent(); // delegate
    public class SimpleClass
        public event OnSimpleEvent SimpleEvent; // event
        public void SimpleMethod()
            SimpleEvent(); // raise the event

There are two classes here. The standard windows generated Form1 and SimpleClass. SimpleClass is our own class with one event and one method.

Inside Form1 we've created a new instance of SimpleClass called SimpleObject.

In Form1's constructor, we've added an event handler (this makes it 'listen' for the specified event and call the specified method) for loading of Form1, and another for our SimpleObject's event. This calls the SimpleEventOccurred method in Form1 when the event is raised.

In Form1's load method we call SimpleObject's SimpleMethod, which is where the event gets raised. This method could be called from anywhere but I've placed it in the Load so it happens immediately when you run the project.

How easy was that?

Experiment Suggestions

Passing parameters: You will often see something similar to this in the signatures of methods called by events:

(object sender, EventArgs e)

If you want to do this or anything similar you will also need to give your delegate the same signature and pass valid paramaters when raising the event i.e.

public delegate void OnSimpleEvent(object sender, EventArgs e);


SimpleEvent(this, EventArgs.Empty); // raise the event


Custom EventArgs: You can create your own class that inherits from System.EventArgs

public class SimpleEventArgs : EventArgs { }

and pass an instance of this class in your parameters. This class can obviously have its own propeties/methods/constructors etc that can be manipulated and/or made accessible to the receiving method.

Return type: The method that gets called by the event handler (private void SimpleEventOccurred() in our case) can return a value type. To do this you will need to specify the same type in your delegate declaration. The call to SimpleEvent() will then be returned a value of type you specified.


more info

Another simple example

No comments:

Post a Comment