.NET Articles

C# Simple example of event


To understand why event is required, think about below scenario.

Assume you are creating a reusable class and this is going to use by other developers as third party class.

Assume there is a requirement like one of the third party class methods should execute the custom method written by the developer. This is possible only through the events. It is amazing that third party class which is predefined and is able to execute the custom method written by the developer.

To write an event what is required is delegate. Delegate is the function pointer which is going to point to custom method written by developer and same will be executed when event is fired from the event class.

First have a look at complete code and output then understand in depth.

Sample of complete Code:

using System;
   
    public delegate void OnBeforeSavingEventHandler(string EmpName,String FatherName);
    public class Customer
    {
        public event OnBeforeSavingEventHandler OnBeforeSaving;        
        public void PerformOperations()
        {
            Console.WriteLine("Execution of third party class method: command 1");
            Console.WriteLine("Execution of third party class method: command 2");

            if (OnBeforeSaving != null)
                OnBeforeSaving(EmpName:"SriRam",FatherName: "Gopal");
            // Same statement can be written like OnBeforeSaving.Invoke("SriRam", DateTime.Now);
            Console.WriteLine("Execution of third party class method: command 3");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer obj = new Customer();
            obj.OnBeforeSaving += BeforeSaving;
            obj.PerformOperations();

            Console.ReadKey();
        }
        public static void BeforeSaving(string EmpName, String FatherName)
        {
            Console.WriteLine("");
            Console.WriteLine("Amazing! Event Fired!! Values before saving");          
            Console.WriteLine("EmpName: " + EmpName + " , Father Name: " + FatherName);
            Console.WriteLine("");

        }
    }
        

Output:

          Execution of third party class method: command 1
          Execution of third party class method: command 2

          Amazing! Event Fired!! Values before saving
          EmpName: SriRam , Father Name: Gopal

          Execution of third party class method: command 3
        

Analysis in depth:

There are 4 steps mainly involved in event.

Step1: Define the delegate. You cannot create event without delegate because delegate is used as function pointer for event. In our code the example is

 
            public delegate void OnBeforeSavingEventHandler(string EmpName,String FatherName);
        

Step2: Define the Event with delegate. Delegate indicates what type of method can be called by event.

            public event OnBeforeSavingEventHandler OnBeforeSaving;
        

Step3: Call the event

            if (OnBeforeSaving != null)
                OnBeforeSaving(EmpName:"SriRam",FatherName: "Gopal");
            // Same statement can be written like OnBeforeSaving.Invoke("SriRam", DateTime.Now);
        

Use of if condition is to find any method has attached to the event and if no method has associated to event then don't fire the event.

Step4: In above steps event declaration and firing the event is over. Now the left out part is associate event with the method in consuming class.

            Customer obj = new Customer();           
           //Attach event to the method
           obj.OnBeforeSaving += BeforeSaving;
        

Any number of methods can be attached to the event using the += operator. When event is invoked all the methods associated to the event will be executed in a sequence.

Hope now you are clear about how event works!