Home > DeveloperSection > Beginner > Delegate and Events in C#

Delegate and Events in C#


C# C# 
Ratings:
0 Comment(s)
 976  View(s)
Rate this:

Delegate and Events in C#


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.


  class DelegateACEvent
    {
        public delegate void ACLog(String status);
        public event ACLog 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,

 


  protected void 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 = new DelegateACEvent();
                ev.ACEventLog += new DelegateACEvent.ACLog(Logger);
                ev.ACEventLog += new DelegateACEvent.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
{
    class AC
    {
          private int RoomTemprature;
          public AC(int rt)
          {
               RoomTemprature = rt;
        }
 
          public int getRoomTemp()
          {
              return RoomTemprature;
        }
    }
   class DelegateACEvent
    {      
       // An  defining a  delegate
        public delegate void ACLog(String status);
        // An event based on the above delegate
        public event ACLog ACEventLog;
      
 public void LogProcess()
        {
            string remark = "O. K.";
            Console.WriteLine("Enter the Room temprature: ");
            int rt = Convert.ToInt32(Console.ReadLine());
            AC ac = new AC(rt);
            rt = ac.getRoomTemp();
            if (rt > 16)
            {
                remark = "AC Started";
            }
            else if (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);
        }
        protected void OnACEventLog(string message)
        {
            if (ACEventLog != null)
            {
                ACEventLog(message);
            }
        }
 
    } 
   //this class for writing into the log file 
   class ACInfo
    {
        FileStream fs;
        StreamWriter sw;
        public ACInfo(string filename)
        {
            fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
        }
        public void Logger(string info)
        {
            sw.WriteLine(info);
        }
        public void Close()
        {
            sw.Close();
            fs.Close();
        }
    } 
     public class Recording
     {
         static void Logger(string info)
         {
                Console.WriteLine(info);
         }
        static void Main(string[] args)
        {
                 string choice = string.Empty;
              do
               { 
                ACInfo file = new ACInfo("ACLog.txt");
                DelegateACEvent ev = new DelegateACEvent();
                ev.ACEventLog += new DelegateACEvent.ACLog(Logger);
                ev.ACEventLog += new DelegateACEvent.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:

 


Don't want to miss updates? Please click the below button!

Follow MindStick