Tech Off Post

Single Post Permalink

View Thread: basic C# question
  • User profile image
    bdesmet

    Maybe it's useful to show a more complete sample containing an event definition as well.

    Let's start with the concept of a delegate, which is an object that can point to a method with a given signature:

    delegate int BinOp(int a, int b);

    BinOp can point to any method that takes two ints and returns an int. For example:

    int Add(int a, int b) { return a + b; }

    can be pointed at by a BinOp delegate, like this:

    BinOp add = new BinOp(Add);

    or even (starting from C# 2.0):

    BinOp add = Add; //the same as the code above, just more convenient

    One can call the target method a delegate is pointing at by using regular method call syntax on the delegate instance, like this:

    add(1,2); //notice the casing of add - we're not calling Add directly but through the delegate created above

    For the following, consider a delegate defined like this:

    delegate void ChangedEventHandler(object o, ChangedEventArgs e);

    Note: there's a generic EventHandler class that provides a shortcut to create typical *EventHandler delegates.


    Now we can cook up an event using this delegate. This allows users of a class to "subscribe" to an event by pointing at a method with the appropriate signature:

    class Controller
    {
       public event ChangedEventHandler StateChanged; //events have a delegate type, in this case ChangedEventHandler

       public void DoWork()
       {
          //do work
          if (StateChanged != null) //make sure someone has subscribed
             StateChanged(this, new ChangedEventArgs(...)); //delegate calling syntax
          //do more work
       }
    }

    This allows the user of the class to subscribe to the event like this:

    Controller ctrl = new Controller();
    ctrl.StateChanged += new ChangedEventHandler(ctrl_Changed);

    where ctrl_Changed is defined like this:

    void ctrl_Changed(object o, ChangedEventArgs e)
    {
       //do something to handle the event; o points at the object that raised the event - you can cast it back to Controller
    }

    Or, using anonymous method syntax in C# 2.0 and higher:

    Controller ctrl = new Controller();
    ctrl.StateChanged += delegate (object o, ChangedEventArgs e)
    {
       //do something to handle the event; o points at the object that raised the event - you can cast it back to Controller
    };

    Hope this helps.