Mar 14 2010

Inheriting EventArgs for better events

Category: EventsMike Lovell @ 10:41 pm

In a lot of cases, you need to return some custom data from your events.  Inheriting from ‘EventArgs’ gives you the opportunity to do this.  Here’s an example of how you do it.  Fortunately this time, it’s all self explanatory.

   1:  // Author Mike Lovell (mike.lovell@gotinker.com)
   2:   
   3:  class Firey
   4:  {
   5:      public class MyEventArgs : EventArgs
   6:      {
   7:          public    bool    IsSomethingNice;
   8:          public    int        SomeNumber;
   9:          public    string    SomeText;
  10:      }
  11:   
  12:   
  13:      public    event    EventHandler<MyEventArgs>    MyEvent;
  14:   
  15:   
  16:      public void FireEvent()
  17:      {
  18:          if (MyEvent != null) MyEvent(this, new MyEventArgs()
  19:              {
  20:                  IsSomethingNice    = true,
  21:                  SomeNumber        = 666,
  22:                  SomeText        = "Hello World"
  23:              });
  24:      }
  25:  }
  26:   
  27:   
  28:   
  29:  class Program
  30:  {
  31:      static void Main(string[] pargs)
  32:      {
  33:          var firey    = new Firey();
  34:   
  35:          firey.MyEvent += delegate(object sender, Firey.MyEventArgs args)
  36:              {
  37:                  Console.WriteLine
  38:                      (
  39:                          "Event Fired:nIsSomethingNice: {0}nSomeNumber: {1}nSomeText: {2}",
  40:                          args.IsSomethingNice,
  41:                          args.SomeNumber,
  42:                          args.SomeText
  43:                      );
  44:              };
  45:   
  46:          firey.FireEvent();
  47:   
  48:          Console.ReadLine();
  49:      }
  50:  }

Download Visual Studio 2010 Project (6.35k)

Leave a Reply