delegates

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi there

I have a delegate that needs to have only 1 function to call. There is a
possibility that the function will be added to the delegate a second time if
the button is clicked twice. Is it "legal" to assign a delegate null before
adding a function to the delegate. eg
del = null;
del += new delfunc();

Thanks
Dave
 
DiamondDavo said:
I have a delegate that needs to have only 1 function to call. There is a
possibility that the function will be added to the delegate a second time if
the button is clicked twice. Is it "legal" to assign a delegate null before
adding a function to the delegate. eg
del = null;
del += new delfunc();

No need to do that - just do:

del = new delfunc();

However, neither of these will work if instead of a delegate variable,
you're actually dealing with an event, which only has
subscribe/unsubscribe behaviour.
 
Jon Skeet said:
No need to do that - just do:

del = new delfunc();

However, neither of these will work if instead of a delegate variable,
you're actually dealing with an event, which only has
subscribe/unsubscribe behaviour.

Hi Jon

Thanks for that. It is actually an event. I tried "del = new delfunc();" but
the compiler barfs with only += and -= are valid. Is there a way I can make
sure it is only assigned once?

Thanks
Dave
 
Thanks for that. It is actually an event. I tried "del = new
delfunc();" but the compiler barfs with only += and -= are valid. Is
there a way I can make sure it is only assigned once?

The best way is to design the problem away - change your design to make
sure that it's only going to be added once in the first place.

Alternatively, keep a flag to say whether or not you've already added
the delegate in question.
 
DiamondDavo schreef:
Hi there

I have a delegate that needs to have only 1 function to call. There is a
possibility that the function will be added to the delegate a second time if
the button is clicked twice.

make the event private, and implement accessor methods to do the
verifications...

private event EventHandler bar;

public event EventHandler Bar
{
add
{
// only subscribe if there aren't other subscribers...
if (this.bar.GetInvocationList().Length == 0)
{
this.bar += value;
}
}

remove { this.bar -= value; }
}
 
DiamondDavo schreef:
Hi there

I have a delegate that needs to have only 1 function to call. There is a
possibility that the function will be added to the delegate a second time if
the button is clicked twice. Is it "legal" to assign a delegate null before
adding a function to the delegate. eg
del = null;
del += new delfunc();

Wrap the event in a property and implement the add method so that it
verifies
 
Tim Van Wassenhove said:
DiamondDavo schreef:

Wrap the event in a property and implement the add method so that it
verifies

Thanks very much Tim and Jon

Thats got me going.

Cheers
Dave
 
Back
Top