> 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.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
DiamondDavo - 13 Apr 2007 06:50 GMT
> > 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
[quoted text clipped - 10 lines]
> 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
Jon Skeet [C# MVP] - 13 Apr 2007 07:31 GMT
<snip>
> 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.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
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; }
}

Signature
Tim Van Wassenhove <url:http://www.timvw.be/>
DiamondDavo schreef:
> Hi there
>
[quoted text clipped - 4 lines]
> del = null;
> del += new delfunc();
Wrap the event in a property and implement the add method so that it
verifies

Signature
Tim Van Wassenhove <url:http://www.timvw.be/>
DiamondDavo - 24 Apr 2007 22:24 GMT
> DiamondDavo schreef:
> > Hi there
[quoted text clipped - 8 lines]
> 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