Delegate Link

Is there a way for a delegate to refer to itself? I am looking for a way to do this:

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

void test() {
    list.Add(delegate() {
        list.Remove(/* this delegate */);
    });
}
+5
source share
2 answers

I'm not sure what you are trying to do, but a delegate can refer like this:

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

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

    foos.Add(del);
}
+13
source

One way is to provide the delegate with an argument for himself:

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 the variable, referring to itself:

Foo foo;
foo = delegate() { list.Remove(foo);}
list.Add(foo);
+2
source

All Articles