1

In C#, how can a closure reference itself? The use case is to automatically unsubscribe from an event, after a single occurrence (or on some condition). I know you can create an instance of a delegate, but I'd really like to keep this as a closure, to maintain context. For example:

var someVar = new FooBar();
textBox1.TextChanged += (s, e) => {
    doSomething(someVar);
    // Unsubscribe from further events
    // textBox1.TextChanged -= myself?
    // If I don't unsubscribe, I'm needlessly keeping reference
    // to someVar, and I don't intend to keep triggering this code
    // upon further events.
};
Edward Ned Harvey
  • 6,525
  • 5
  • 36
  • 45
  • I believe you'll have to actually put `doSomething` in an actual event, as you cannot remove the subscription with this; `textBox1.TextChanged = null`. So you'll need an actual method / event to remove. – sab669 Nov 12 '15 at 19:21

1 Answers1

1

As far as I know it cannot reference itself directly. However, you do something like this instead:

var someVar = new FooBar();
EventHandler closure = null;
closure = (s, e) => {
    doSomething(someVar);
    // Unsubscribe from further events
    // textBox1.TextChanged -= myself?
    // If I don't unsubscribe, I'm needlessly keeping reference
    // to someVar, and I don't intend to keep triggering this code
    // upon further events.
    textBox1.TextChanged -= closure;
};
textBox1.TextChanged += closure;

Credit: Can an anonymous method in C# call itself?

Community
  • 1
  • 1
rmblstrp
  • 254
  • 3
  • 10