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 */);
});
}
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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With