3

How to use the this (or something of that kind) referring to the delegate instance instead of the class instance ?

instance.OnEventFoo += delegate()
    {
        if (condition)
        {
            instance.OnEventBar += this;
        }
    };
56ka
  • 1,463
  • 1
  • 21
  • 37

2 Answers2

4

Since you can't refer to a variable before it is declared, you have to:

  1. first declare the variable,
  2. then assign a delegate,
  3. then register the handler with the event.

// Add an anonymous delegate to the events list and auto-removes automatically if item disposed
DataRowChangeEventHandler handler = null;
handler = (sender, args) =>
    {
        if (condition)
        {
            // need to remove this delegate instance of the events list
            RowChanged -= handler;
        }
    };

something.RowChanged += handler;
dcastro
  • 66,540
  • 21
  • 145
  • 155
3

You need to store it in a variable somewhere. For example:

EventHandler rowChanged = null; // to avoid "uninitialized variable" error

rowChanged = (s, e) =>
{
    if (condition)
    {
        // this will unsubscribe from the event as expected
        RowChanged -= rowChanged;
    }
};
Jon
  • 428,835
  • 81
  • 738
  • 806