1

I've got following problem: (c#)

There is some class (IRC bot), which has method, which needs result of some event for complete (through it could be asynchronous).

Maybe not clear:

// simplified
class IRC 
{
 void DoSomeCommand()
 {
  OnListOfPeopleEvent += new Delegate(EventData e) { 
   if (e.IsForMe)
   {
    ReturnToUserSomeData();
    // THIS IS WHAT I NEED
    OnListOfPeopleEvent -= THIS DELEGATE;
   }
  }
  TakeListOfPeopleFromIrc();
 }
}

And I want to delete that delegate when it the function is complete. Is there any way how to obtain the reference to closure in it itself?

nothrow
  • 15,882
  • 9
  • 57
  • 104

1 Answers1

4

You can do this with a cheaky variable that captures itself ;-p

SomeDelegateType delegateInstance = null;
delegateInstance = delegate {
    ...
    obj.SomeEvent -= delegateInstance;
};
obj.SomeEvent += delegateInstance;

The first line with null is required to satisfy definite assignment; but you are allowed to capture this variable inside the anon-method.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I found this solution like kind of a hack, but sufficient for me. Thanks. ( Cleaner would be solution which isn't dependent on explicitly named variable :) ) – nothrow Jul 07 '09 at 09:42
  • If you don't name the variable, you'd have to name the method instead, and handle all the state transfer... – Marc Gravell Jul 07 '09 at 09:56