views:

67

answers:

1

Hello, 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?

+4  A: 

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
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 :) )
Yossarian
If you don't name the variable, you'd have to name the method instead, and handle all the state transfer...
Marc Gravell