Skip navigation

OK, this one is a bit more complex, so start here, then go there.

WHY C# events

An EVENT in C# is simply a means to create a CHAIN of functions that will execute when something “happens” to an object.

OBJECT with published event
subscriber 1 subscriber 2 subscriber 3 subscriber 4 subscriber 5

EVENTS in C# follow the observer design pattern. The object that CONTAINS the “event” is the “PUBLISHER”, while all the objects that “attach a function” to the event are “subscribers” to that event.

Understanding C# custom events

As a prerequisite to understanding this, you must have already worked with normal events in C#, and built a couple of simple windowed applications using .NET. If not, go read up on them, also try this.

In fact, let me summarize the prereqs to understanding this article here:

  • Worked with events in C# normally before (windows forms applications)
  • Understands delegates

If you don’t have those prereqs, RUN AWAY!! This will not make any sense to you, especially if you don’t understand delegates at all.

Custom events are great!

The point of defining custom events in C# is to provide an EASY MECHANISM to have a chain of functions that will execute in rapid succession on your command.

The idea is this. You have an object, say a BUTTON. WHEN THAT BUTTON IS CLICKED by the user, you want some function to run. But wait, not just ONE function. You want SEVERAL functions to run. In rapid succession, one after the other. AND YOU WANT THEM TO RUN WHEN THE BUTTON IS CLICKED!

So here’s what you do. You define an EVENT

using System;


public class Button
{
  // Define the EVENT here.
  public event Action Pushed ;

  // NOTICE how we specify the ACTION delegate
  // in this declaration.

  // The ACTION delegate use means that 
  // the "Pushed" event accepts a chain of
  // functions to be attached to it that all have
  // NO arguments, and return type VOID.

  // You can use ANY DELEGATE TYPE YOU WANT for
  // an event in C#.  You can define your own
  // delegate type if you want, but you will really
  // have to study and understand delegates if you
  // want to do that (not covered here!)



  // This is the function that triggers the event.
  public void PushButton()
  {
    // Print out a message before actually firing the
    // Pushed event.
    Console.WriteLine("Oh, you pushed me.");
    
    // !! VERY IMPORTANT LINE!!
    Pushed();  // "FIRE" EVENT:  CAUSES ALL FUNCTIONS THAT WERE ATTACHED
    // TO THE "Pushed" EVENT PREVIOUSLY TO EXECUTE IN
    // RAPID SUCCESSION, ONE AFTER THE OTHER!

    // The funny thing about Events is the WEIRD, WEIRD, WEIRD
    // syntax is uses.  At one moment, you're +='ing to it,
    // the next moment, you're calling it as if it were a function.

    // Strictly speaking, the Pushed event ISN'T a function.
    // Its a series of functions.. internally it must be some
    // kind of object with some kind of linked list inside.  But
    // in any case, this notation takes some getting used to,
    // but once you're used to it, it makes a whole lotta sense.

    // ALSO, take note that YOU MUST "FIRE" THIS EVENT FROM
    // WITHIN THE Button CLASS!

    // YOU __CANNOT__ "FIRE" AN EVENT OUTSIDE THE CLASS IN WHICH
    // THAT EVENT IS DECLARED.  I explain this in more detail
    // below.

    // Finally, print out another message after firing all
    // event functions.
    Console.WriteLine("Great, now my paint is all dented");
  }
}


public class Program
{
  // one function that will be attached
  // to the Button's Pushed event.  Notice
  // it can be attached because it has
  // no arguments and return type void.
  public static void ButtonPusher()
  {
    Console.WriteLine("HI THERE!!");
  }

  // another function that will be attached
  // to the button's Pushed event
  public static void func2()
  {
    Console.WriteLine("HELLO!!");
  }

  // notice because of our use of the ACTION delegate
  // type in the Pushed event declaratino, we CANNOT
  // attach THIS functino to the Pushed event.  THe
  // signature of functions you attach to the Pushed event
  // MUST MATCH the signature of the delegate type you used
  // in the declaration of the event.  In this case the Pushed
  // event uses the Action delegate type, which is defined
  // in the .NET framework to be a delegate of return type void,
  // and accepts no arguments.
  public static void sayHi( int howMany )
  {
    Console.WriteLine( howMany + " hi's to yoU!" ) ;
  }

  static void Main( string[] args )
  {
    Button b = new Button();

    // Attach 3 functions to execute
    // when the Pushed event fires
    // from within the button
    b.Pushed += new Action( ButtonPusher );

    b.Pushed += new Action( func2 );

    b.Pushed += new Action( ButtonPusher );

    // Illegal:  sayHi does not match the Action delegate type,
    // and the Pushed event requires that the functions chained on
    // match the Action delegate type.
    ////////b.Pushed += new Action( sayHi ) ;

    // now push the button, (which in turn,
    // FIRES THE EVENT)
    b.PushButton();


    // Finally, notice this is illegal
    /////b.Pushed() ;
    // The error is:
    // Error 1 The event 'Button.Pushed' can only appear on the
    // left hand side of += or -= (except when used from
    // within the type 'Button')
    
    // Reason:  basically the EVENT member itself
    // is kind of private to the class.  You're not
    // allowed to "invoke it" from outside the Button class.

    // But you can, as we did here, define a function
    // within the Button class that in turn, invokes/fires
    // the event.

  }

}


I think events are rooted in the observer pattern, but you don’t have to know the observer pattern to apply what we’re working on here.

Ah, so, declaring a custom event in C# is fun. To summarize, here’s what you need:

1. A public delegate, which effectively specifies the type of function (argument list, return type) that can be chained onto the event. In this example, we just used the .NET defined Action delegate, which has return type void and no arguments passed to it.
2. Declaration of the event itself, inside the class that the event can “happen to”
3. Lastly, you TRIGGER the event from within the class in which the event is declared. You MAY NOT trigger the event from outside the class in which it is declared (you may NOT type eventName() OUTSIDE THE CLASS, EVER.)

About these ads

8 Comments

    • Anonymous
    • Posted January 16, 2010 at 11:03 am
    • Permalink

    Color of your page is not good please change it.

    • Anonymous2
    • Posted December 23, 2011 at 4:59 pm
    • Permalink

    Color of your page is nice, thanks.

    • Jake
    • Posted February 24, 2012 at 6:51 am
    • Permalink

    Nice post , bad choice of color ,thanks anyway its very useful

    • Anonymous
    • Posted May 6, 2012 at 6:48 pm
    • Permalink

    finally i found it here !! its simple easy !!:)

    • shravanthi
    • Posted June 4, 2012 at 8:04 am
    • Permalink

    I’ve tried understanding these events in many web pages.Finally this page has helped me a lot. Thanks!!

    • ishu
    • Posted June 26, 2012 at 10:29 am
    • Permalink

    Superbe page designing..! choice of colour is excellent..
    I was really eager to read it when I saw this page.
    And finally i understood it completely.

    • Anonymous
    • Posted July 2, 2012 at 1:08 am
    • Permalink

    FINALLY someone who has explained events to me in a way that is simple, easy to understand, and concise. Thank you!

    • Piotr
    • Posted July 19, 2013 at 6:24 am
    • Permalink

    Like the comment above – finally I understood, uhmpff…
    Colouring is fine.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 37 other followers

%d bloggers like this: