Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate reference itself

Tags:

c#

delegates

Is there a way for a delegate to reference itself? I'm looking for a way to do this:

delegate void Foo();
list<Foo> foos;

void test() {
    list.Add(delegate() {
        list.Remove(/* this delegate */);
    });
}
like image 220
sharvey Avatar asked Sep 08 '11 21:09

sharvey


2 Answers

I'm not sure exactly what you're trying to do, but it's possible for a delegate to reference itself like this:

delegate void Foo();
List<Foo> foos = new List<Foo>();

void test() {
    Foo del = null;
    del = delegate { foos.Remove(del); };

    foos.Add(del);
}
like image 56
LukeH Avatar answered Sep 24 '22 07:09

LukeH


One way is for the delegate to accept an argument for itself:

delegate void Foo(Foo self);
...
list.Add(delegate (Foo self) { list.Remove(self);});
...
foreach (Foo f in list) f(f);

Another way would be to close over a variable refering to itself:

Foo foo;
foo = delegate() { list.Remove(foo);}
list.Add(foo);
like image 45
Mark Cidade Avatar answered Sep 24 '22 07:09

Mark Cidade