How to Create Custom Event in C#

Let's consider the following example; we will try to create a custom event for a string variable:

  1. Event should be raised whenever the value of string changes.
  2. Event should not be raised if the value is null or the same as the previous value.
  3. Event should provide the following information.
    • Time at valued changed
    • Previous value in the string
    • Current value of string
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. usingSystem.Collections.Concurrent;  
  6. using System.Collections;  
  7.    
  8. namespace Rough_use  
  9. {  
  10.     classProgram  
  11.     {  
  12.         public int a = 0;  
  13.         public static void Main(string[]args)  
  14.         {  
  15.               dele newdele = newdele();  
  16.               newdele.namehaschanged+= new dele.namechange(gottheevent); //subscribing to event published by "dele" class  
  17.               Console.WriteLine("Haries");  
  18.               newdele.Riseevent= "Haries";  
  19.               Console.WriteLine("Vimal");  
  20.               newdele.Riseevent= "Vimal";  
  21.               Console.ReadKey();  
  22.         }  
  23.         static void gottheevent(Type o, Stringvaluechangedevente)        //this is theevent which will be raised when the value of string changes  
  24.         {  
  25.             Console.WriteLine("    Time of Changing          -" +e.changedat.ToString());  
  26.             Console.WriteLine("    Current Value set         -" +e.currentvalue.ToString());  
  27.             Console.WriteLine("    Previous Value Overiden    -" +e.previous.ToString());  
  28.         }  
  29.    }  
  30.    public class Stringvaluechangedevent : EventArgs      //this is the event details  will be sent while the value of   string "Riseevent" changes  
  31.    {                                                     //EventArgs - is nothing but an empty class from which all event are derived  
  32.         publicDateTime changedat;  
  33.         publicstring previous;  
  34.         publicstring currentvalue;  
  35.         publicStringvaluechangedevent(DateTime changeda, string previou, stringcurrentvalu) // setting the value to parameter that are sent in event class  
  36.         {                                                                                                                                                                                                                                                                                  //  
  37.               this.changedat = changeda;  
  38.               this.previous = previou;  
  39.               this.currentvalue = currentvalu;  
  40.         }  
  41.    }  
  42.    classdele  
  43.    {  
  44.         public delegate void namechange(Type o, Stringvaluechangedevente);  //declaring a simple delegate  
  45.         public event namechangenamehaschanged;                              //  creating the instant for delegate that is declared  
  46.         private string riseevent = "";  
  47.         public string Riseevent  
  48.         {  
  49.             get { return riseevent; }  
  50.             set  
  51.             {                                                           //main story starts here!!!  
  52.                   if (value!= null && value != riseevent)               // if the values of string is set null or the value is set to same previous value then  we should not rise the event  
  53.                   {                       
  54.                        Stringvaluechangedevent e = new Stringvaluechangedevent(DateTime.Now, riseevent, value.ToString());//initiating the value that are sent to along with event         
  55.                        if (namehaschanged != null)                     //checking whether  there are subscriber tothis event  
  56.                        {  
  57.                            namehaschanged(Riseevent.GetType(),e);     // rising the event ..ie sent signaling to all subscriber ofthe this  event  
  58.                        }  
  59.                   }  
  60.                   riseevent= value;      // finally setting the value to string  
  61.             }  
  62.       }  
  63.    }  
  64. }   
Details
  • dele is a class that wraps the string “Riseevent” that is responsible for publishing the event.

  • public delegate void namechange(Typeo, Stringvaluechangedevent e);

    This is the simple delegate signature. So any method that subscribes to this event should be of the same format. It should have two parameters of Type and Stringvaluechangedevent where Stringvaluechangedevent is a custom event that we have created.

  • public event namechangenamehaschanged;

    This is the instance of the delegate namechange.

  • When the value of the string Riseevent changes we will fire the event. Hence to accompanies this task we will fire the event in the “set” property.

  • if (value != null&& value != riseevent)

    Here we are checking whether the value is null or the same as the previous value.

  • if(namehaschanged != null)

    Here we are checking whether there is any subscriber for this event.

  • Stringvaluechangedevent e = new Stringvaluechangedevent(DateTime.Now, riseevent, value.ToString())

    This line of code is very important. We are creating an instance of the custom class Stringvaluechangedevent. In the constructor we are ing the information that should be given to subscriber.

    changedat

  • So these (changedat, previous, currentvalue) will be sent to the subscriber.

  • Stringvaluechangedevent is the class that is ed as the custom event to the subscriber.

Important

  • public event namechangenamehaschanged;

    Here if we remove the Event keyword then the subscriber will have an extra privilege to assign directly to the delegate.
    1. newdele.namehaschanged += new dele.namechange(gottheevent);   
    Instead of the preceding format you can just use:
    1. newdele.namehaschanged = new dele.namechange(gottheevent);   
    So what happens here is that any subscriber that is already subscribed to this delegate will be removed and the only “gottheevent” will be a member of the delegate.

  • Finally the third-party class has an extra privilege over the “dele” class. So to limit his privilege I am using the event keyword.

    error

So the subscriber can only subscribe and unsubscribe to my namechange event rather than allowing him to take control over the namechange. The delegate “event” keyword provides extra security to the delegate.

Up Next
    Ebook Download
    View all
    Learn
    View all