1

I have a case where I want a given event to execute once, and only once. I'm trying to do it this way, but I'm having prolems (else I wouldn't be asking). Note that the following code is inside the function that decides that the event needs to be fired.

EventHandler h = delegate(Object sender, EventArgs e) {
  FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h"
  // Do stuff
}
FiringControl.TheEvent += h;

In general this should work because of the way scope is preserved for delegates until after they're done running, but, since h is in the process of being built when I try to use it it is still considered to be "uninitialized", apparently.

Donnie
  • 45,732
  • 10
  • 64
  • 86
  • http://stackoverflow.com/questions/1554845/am-i-using-the-right-approach-to-monitor-the-tasks-i-want-to-perform-when-a-handl/1554978#1554978 – Juliet Jun 03 '10 at 18:39

1 Answers1

3

You could set h = null first and then set it equal to something else? Like this?

EventHandler h = null;

h = delegate(Object sender, EventArgs e) {
  FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h"
  // Do stuff
}

FiringControl.TheEvent += h;

But are you sure this is the right approach? What are you trying to do overall?

Donnie
  • 45,732
  • 10
  • 64
  • 86
Jason Kleban
  • 20,024
  • 18
  • 75
  • 125
  • Yeah, that works perfect. Had just figured it out and was coming back to delete the question, but I guess I won't now. ;) – Donnie Jun 03 '10 at 17:32
  • As for what I'm doing, I'm temporarily hooking into `TheEvent` to potentially cancel another operation. The "problem" is that there could be multiple of these happening at once, so I abuse local scope binding with delegates to avoid having to maintain a list of these. – Donnie Jun 03 '10 at 17:33