Event in C#

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);
            objAlarmClock.SixAM();
            objAlarmClock.FivePM();
            Console.ReadLine();
        }
    }

    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);
                    
                    switch(args.Time){
                        case 6:
                            Console.WriteLine("{0} is waking!", _Name);
                            break;
                        case 17:
                            Console.WriteLine("{0} is going home from office!", _Name);
                            break;
                    }
            };
                
            }
        }

    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.

Advertisements

#event