Skip Navigation Links.
C# - Raising Events from a Class
Language(s):C#
Category(s):Events
This article shows you how to raise events from a class.

My last article showed how to declare C# events for a Form or Control. This article shows how to declare and raise events from a class.

Before you can use an event in C#, you need to understand the idea of a delegate. Simply put, a delegate is simply a declaration of a type of function. For example, suppose we want to declare an event that will send a status message to the user. We would first declare a delegate with the signature of the event. For example:

        public delegate void StatusMessage(string strMessage);

This looks similar to a function declaration but is not declaring a function but rather a type of function. With this statement, you are telling the compiler, "when I use the word 'StatusMessage' I am referring to a void function with a single parameter of string."

This looks similar to a function declaration but is not declaring a function but rather a type of function. With this statement, you are telling the compiler, "when I use the word 'StatusMessage' I am referring to a void function with a single parameter of string."

This looks similar to a function declaration but is not declaring a function but rather a type of function. With this statement, you are telling the compiler, "when I use the word 'StatusMessage' I am referring to a void function with a single parameter of string."

This looks similar to a function declaration but is not declaring a function but rather a type of function. With this statement, you are telling the compiler, "when I use the word 'StatusMessage' I am referring to a void function with a single parameter of string."

Next, we tell the compiler that this class is going to have an event that matches the signature we just declared above:

Next, we tell the compiler that this class is going to have an event that matches the signature we just declared above:

Next, we tell the compiler that this class is going to have an event that matches the signature we just declared above:

Next, we tell the compiler that this class is going to have an event that matches the signature we just declared above:

        public event StatusMessage SendMessage;

        public event StatusMessage SendMessage;

        public event StatusMessage SendMessage;

        public event StatusMessage SendMessage;

So just to make sure we are on the same page - I have declared a type of function named 'StatusMessage.' I have declared an event called 'SendMessage' that has the same characteristics of the delegate I named 'StatusMessage.'

So just to make sure we are on the same page - I have declared a type of function named 'StatusMessage.' I have declared an event called 'SendMessage' that has the same characteristics of the delegate I named 'StatusMessage.'

So just to make sure we are on the same page - I have declared a type of function named 'StatusMessage.' I have declared an event called 'SendMessage' that has the same characteristics of the delegate I named 'StatusMessage.'

So just to make sure we are on the same page - I have declared a type of function named 'StatusMessage.' I have declared an event called 'SendMessage' that has the same characteristics of the delegate I named 'StatusMessage.'

The event is raised by simply invoking the method itself, with one caveat: You must first make sure the message has been declared by the caller, or you will throw an exception. So, raising the SendMessage event would be done as follows:

The event is raised by simply invoking the method itself, with one caveat: You must first make sure the message has been declared by the caller, or you will throw an exception. So, raising the SendMessage event would be done as follows:

The event is raised by simply invoking the method itself, with one caveat: You must first make sure the message has been declared by the caller, or you will throw an exception. So, raising the SendMessage event would be done as follows:

The event is raised by simply invoking the method itself, with one caveat: You must first make sure the message has been declared by the caller, or you will throw an exception. So, raising the SendMessage event would be done as follows:

        if (SendMessage != null)

            SendMessage(strMessage);

To demonstrate the idea, let's create a simple class that returns an event with a single string as a parameter - like the example above. This class will have an event that sends us back a reminder after a certain number of seconds. So the method will accept a message and an integer indicating the number of seconds to wait. When the time has elapsed, the event will be raised.

To demonstrate the idea, let's create a simple class that returns an event with a single string as a parameter - like the example above. This class will have an event that sends us back a reminder after a certain number of seconds. So the method will accept a message and an integer indicating the number of seconds to wait. When the time has elapsed, the event will be raised.

To demonstrate the idea, let's create a simple class that returns an event with a single string as a parameter - like the example above. This class will have an event that sends us back a reminder after a certain number of seconds. So the method will accept a message and an integer indicating the number of seconds to wait. When the time has elapsed, the event will be raised.

To demonstrate the idea, let's create a simple class that returns an event with a single string as a parameter - like the example above. This class will have an event that sends us back a reminder after a certain number of seconds. So the method will accept a message and an integer indicating the number of seconds to wait. When the time has elapsed, the event will be raised.


Here is a simple implementation of the Reminder method:

        public void RemindMeLater(int intSeconds, string strMessage)

        public void RemindMeLater(int intSeconds, string strMessage)

        public void RemindMeLater(int intSeconds, string strMessage)

        public void RemindMeLater(int intSeconds, string strMessage)

        {

            DateTime dteStop = DateTime.Now.AddSeconds(intSeconds);

            while (DateTime.Now.CompareTo(dteStop) < 0)

System.Windows.Forms.Application.DoEvents();

            if (SendMessage != null)

                SendMessage(strMessage);

        }

 

 

 

 

 

We'll look at a better way to do this later, but for now, let's see how we would declare the SendMessage event in the calling program.

First of all, we need to declare a method in that matches the signature of the event that will run when the event is raised. For example:

First of all, we need to declare a method in that matches the signature of the event that will run when the event is raised. For example:

First of all, we need to declare a method in that matches the signature of the event that will run when the event is raised. For example:

First of all, we need to declare a method in that matches the signature of the event that will run when the event is raised. For example:

        private void Handle_SendMessage(string strMessage)

        private void Handle_SendMessage(string strMessage)

        private void Handle_SendMessage(string strMessage)

        private void Handle_SendMessage(string strMessage)

        {

            MessageBox.Show(strMessage);

        }

Then we connect the event to this method using the += operator:

        Reminder reminder = new Reminder();

        reminder.SendMessage += Handle_SendMessage;

That's all there is to it - but before we wrap things up - I feel compelled to show a better solution for the RemindMeLater method. Instead of going into a loop, it would be better to use a Timer object. Let's look at how we would do this.

For this solution, we will need to declare two class variables - one to store the message and another for the Timer object:

        private string mstrMessage = null;

        private System.Timers.Timer tmrRemider = null;

We will next repeat the process above and declare an event handler for the Timer. We will set the timer to go off after the number of seconds specified by the user - at which time we will raise the SendMessage event. The Timer constructor accepts a double parameter that represents the number in miliseconds. The object also raises an 'Elapsed' event which will raise when the value specified in the constructor has been elapsed.

The Elapsed event accepts an object as well as a System.Timers.ElapsedAventArgs parameter. When the event fires, we will want to stop the timer and then raise the SendMessage event back to the caller:

private void tmrRemider_Elapsed(object sender,

System.Timers.ElapsedEventArgs e)

        {

             tmrRemider.Enabled = false;

 

 

 

 

 

            if (SendMessage != null)

                SendMessage(mstrMessage);

        }

It is important to set the Enabled propery prior to raising the event, or it won't execute and the Elapsed event will continue to fire.

     

Now our improved RemindMeLater function looks like this:

        public void RemindMeLater2(int intSeconds, string strMessage)

        {

            mstrMessage = strMessage;

            tmrRemider = new System.Timers.Timer((double)intSeconds * 1000);

            tmrRemider.Elapsed += tmrRemider_Elapsed;

            tmrRemider.Enabled = true;

        }

The sample downloadable project conains all the code for as well as a simple test program to demonstrate the instantiating the class, calling the methods and retrieving the events. Enjoy!

 

Next C# - Webforms Events

 

 

This article has been viewed 7650 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.