tags:

views:

47

answers:

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.

+3  A: 

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?

uosɐſ
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
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