Monday, November 19, 2012

Easy way to have a class publish an event

This is an easy way to have a class fire an event. First declare the event as an Action<> in the class.

public class MyClass
{
    public event Action<int, string> MyEvent;
    public event EventHandler<bool> MyOtherEvent; 
 
    public MyClass()
    {
    }
    private void MyMethod(int i, string s, bool b)
    {
        // an exception will be thrown if you attempt to fire an event 
        // when there are no subscribers to the event, so we need to 
        // check first
        if (MyEvent != null)
            MyEvent(i,s);  // fires the event
                                                    
           MyOtherEvent?.Invoke<this, b>;   
    }
}

To consume the event, just declare a handler for it after instantiating the class.

    MyClass mc = new MyClass();
    mc.MyEvent += new Action(mc_MyEvent);
    mc.MyOtherEvent += Mc_MyOtherEvent;

   void mc_MyEvent(int i, string s)
   {

   }

   private static void Mc_MyOtherEvent(object sender, bool e)
   {
       
   }

No comments:

Post a Comment