articles

Home / DeveloperSection / Articles / Delegate and Events in C#

Delegate and Events in C#

Anupam Mishra4187 21-Dec-2015

In C#, an event is a way for a class to provide notifications to clients of that class when something happens to an object. The most familiar use for events is in graphical user interfaces (GUI) (for example, click a button, key press, mouse movements etc.).Applications need to respond to event when they occur.

An Events are declaring using by delegates. Delegate methods should be called when the event occurs. The events are declared and raised in a class and associated with the event handler using delegates within the same class or some other class.

  classDelegateACEvent
    {
        publicdelegatevoidACLog(String status);
        publiceventACLog ACEventLog;
     }


Firstly you are insuring to events that event is occur or not? For insuring the caller is registered with its delegate event or not. For this reason we checking, 

 protectedvoid OnACEventLog(string message)
        {
            if (ACEventLog != null)
            {
                ACEventLog(message);
            }
        }

  When you want to register an event handler with an event you must follow this pattern:

       DelegateACEvent ev = newDelegateACEvent();
                ev.ACEventLog += newDelegateACEvent.ACLog(Logger);
                ev.ACEventLog += newDelegateACEvent.ACLog(file.Logger);

Let's see a full example:

In this example, we declare a class AC that record a temperature of the room and another class DelegateACEvent that define delegate method and its event . An event is occur when room temperature is 17 or above AC automatically started if temperature is below then stop the AC and all things recorded a log file. 

using System;
using System.IO;
namespace ACEventEx
{
    classAC
    {
          privateint RoomTemprature;
          public AC(int rt)
          {
               RoomTemprature = rt;
        }
 
          publicint getRoomTemp()
          {
              return RoomTemprature;
        }
    }
   classDelegateACEvent
    {      
       // An  defining a  delegate
        publicdelegatevoidACLog(String status);
        // An event based on the above delegate
        publiceventACLog ACEventLog;
      
 publicvoid LogProcess()
        {
            string remark = "O. K.";
            Console.WriteLine("Enter the Room temprature: ");
            int rt = Convert.ToInt32(Console.ReadLine());
            AC ac = newAC(rt);
            rt = ac.getRoomTemp();
            if (rt > 16)
            {
                remark = "AC Started";
            }
            elseif (rt <= 16)
            {
                remark = "AC Stopped";
            }
            OnACEventLog("\n......................................\n");
            OnACEventLog("\n Loging Info: \n");
            OnACEventLog("\n Room Temparature " + rt);
            OnACEventLog("\nMessage: " +remark);
            OnACEventLog("\nTime: " + DateTime.Now);
        }
        protectedvoid OnACEventLog(string message)
        {
            if (ACEventLog != null)
            {
                ACEventLog(message);
            }
        }
 
    } 
   //this class for writing into the log file 
   classACInfo
    {
        FileStream fs;
        StreamWriter sw;
        public ACInfo(string filename)
        {
            fs = newFileStream(filename, FileMode.Append, FileAccess.Write);
            sw = newStreamWriter(fs);
        }
        publicvoid Logger(string info)
        {
            sw.WriteLine(info);
        }
        publicvoid Close()
        {
            sw.Close();
            fs.Close();
        }
    } 
     publicclassRecording
     {
         staticvoid Logger(string info)
         {
                Console.WriteLine(info);
         }
        staticvoid Main(string[] args)
        {
                 string choice = string.Empty;
              do
               { 
                ACInfo file = newACInfo("ACLog.txt");
                DelegateACEvent ev = newDelegateACEvent();
                ev.ACEventLog += newDelegateACEvent.ACLog(Logger);
                ev.ACEventLog += newDelegateACEvent.ACLog(file.Logger);
                ev.LogProcess();
                Console.ReadLine();
                file.Close();
                Console.WriteLine("Do you want to recheck AC status? y/n");
                choice = Console.ReadLine();
                Console.Clear();
            } while (choice.Equals("y", StringComparison.OrdinalIgnoreCase));
        }
 }}
Output:
Delegate and Events in C#

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By