---
title: "Delegate and Events in C#"  
description: "In C#, an event is a way for a class to provide notifications to clients of that class when something happens to an object."  
author: "Anupam Mishra"  
published: 2015-12-21  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/11963/delegate-and-events-in-c-sharp  
category: "c#"  
tags: ["c#"]  
reading_time: 3 minutes  

---

# 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](https://answers.mindstick.com/qa/102632/what-is-the-significance-of-google-s-material-design-for-user-interfaces) (GUI) (for example, click a button, key press, mouse movements etc.).[Applications](https://www.mindstick.com/articles/12847/how-to-choose-the-right-ethernet-cable-for-industrial-applications) need to respond to event when they occur.\

An Events are declaring using by delegates. [Delegate methods](https://www.mindstick.com/forum/33819/getting-cell-index-number-of-collection-view-from-out-side-the-delegate-methods-in-ios) should be called when the event occurs. The events are declared and raised in a class and associated with the [event handler](https://www.mindstick.com/forum/1371/c-sharp-dot-net-event-handler-delegate-question) 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](https://answers.mindstick.com/qa/106939/what-is-the-hospital-room-temperature-usually-set-to) 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:

##### ![Delegate and Events in C#](https://www.mindstick.com/mindstickarticle/419f38a4-215e-4536-97f5-5db900a8891e/images/d38007c8-434e-4962-8569-bdfd174d436c.png)\

---

Original Source: https://www.mindstick.com/articles/11963/delegate-and-events-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
