Event in C#   Leave a comment

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.

Typically events used with the classes which represents the controls (user interface) like to notify to take some action when user does something with the control.

for example: click event of button.

Events provide a useful way for objects to signal state changes that may be useful to clients of that object.

To understand the above concept lets take an example of Person and AlarmClock.

In below example, I have created two classes Person and AlarmClock. In AlarmClock I have created the event AlarmEvent which will be trigger and notify the Person object if something happens with AlarmClock.

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

namespace Event
    class Program
        static void Main(string[] args)
            AlarmClock objAlarmClock = new AlarmClock();
            Person WhiteX = new Person("WhiteX", objAlarmClock);

    class Person
        private string _Name;
        public Person(string name, AlarmClock alarmClock)
            _Name = name;
            alarmClock.AlarmEvent += (object sender, AlarmEventArgs args) => {
                    Console.WriteLine("{0} heard the alarm!", _Name);
                        case 6:
                            Console.WriteLine("{0} is waking!", _Name);
                        case 17:
                            Console.WriteLine("{0} is going home from office!", _Name);

    public delegate void AlarmEventHandler(object sender, AlarmEventArgs args);

    public class AlarmEventArgs : EventArgs {
        public AlarmEventArgs() { 
        public int Time { get; set; }

    class AlarmClock
        public AlarmClock() { 

        public event AlarmEventHandler AlarmEvent;
        public void FivePM() {

            AlarmEvent(this, new AlarmEventArgs { Time = 17 });

        public void SixAM() {
            AlarmEvent(this, new AlarmEventArgs { Time = 6 });


There are many other usage of the events in C#, here we have discussed the simple use to notify the other object if there is change in state in another related object.


Posted November 23, 2014 by Izharuddin Shaikh in C#

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: