How To Create your Own Custom Events in C#

In this post, I will show how to extend EventArgs class.

  • Create your custom event args class derived from System.EventArgs
  • Declare your delegate with two parameters, object source and YourEventArgsClass e
  • Create a protected virtual method that fires the event for you (its protected and virtual so that deriving class can see the method and also override it if they wish to change how and when the event is fired)
using System;

public class MyEventArgs : System.EventArgs
{
   private bool m_OldValue;
   private bool m_NewValue;

   public MyEventArgs(bool oldVal, bool newVal)
   {
       this.m_OldValue = oldVal;
       this.m_NewValue = newVal;
   }

   public bool OldValue
   {
       get { return this.m_OldValue; }
   }

   public bool NewValue
   {
       get { return this.m_NewValue; }
   }
}
public class MyClass
{
   public delegate void ValueChangedHandler(object source, MyEventArgs e);
   public event ValueChangedHandler ValueChanged;

   private bool m_MyBool = false;

   public MyClass() { }

   public void SomeMethod()
   {
       this.MyBool = true;
   }

   public bool MyBool
   {
       get { return this.m_MyBool; }
       set
       {
           //Now call our virtual method, with the old and new value (this fires the event for us)
           this.OnValueChanged(new MyEventArgs(this.m_MyBool, value));
           this.m_MyBool = value;
       }
   }

   protected virtual void OnValueChanged(MyEventArgs e)
   {
       this.ValueChanged(this, e);
   }
}

class Test
{


   public static void Main()
   {

       MyClass obj = new MyClass();
       obj.ValueChanged += new MyClass.ValueChangedHandler(obj_ValueChanged);
       obj.SomeMethod();
       Console.Read();

   }

   static void obj_ValueChanged(object source, MyEventArgs e)
   {
       if (e.NewValue == false)
       {
           Console.WriteLine("Hi");
           Console.Read();
       }
       else
       {
           Console.WriteLine("bye");
           Console.Read();
       }
   }

}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru