Search code examples
c#closuresanonymous-methods

Accessing 'self' object in closure


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?


Solution

  • 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.