PLS HELP:Managing events

M

MuZZy

Hi,

I'm developing a usercontrol which has an event SelectedValueChanged.
Below is the simple version of what i have:

//------------------------------
class SelectedValueChangedArgs: EventArgs
{
object m_oValue;
public SelectedValueChangedArgs(object oValue)
{
m_oValue = oValue;
}
public object Value {get{return m_oValue;}}
}
//--
public delegate SelectedValueChangedHandler(object sender,
SelectedValueChangedArgs e);
//--
public MyControl{
public SelectedValueChangedHandler SelectedValueChanged;
}
//-----------------------------------

The problem is that i have to make sure that any event handler added to
that event is added only once, so i should use it like this:

SelectedValueChangedHandler h = new
SelectedValueChangedHandler(SomehandlerFundction);

myControl.SelectedValueChanged -= h;
myControl.SelectedValueChanged += h;

But the problem is that i can't control all 30 developers in the company
and i ended up spending the whole weekend cleaning up after them (adding
-= to make sure the handler is not added second time somewhere).

So now i'm thinking of making the event protected and creating a
function which will be adding a handler:

// -------- CODE ---------
class MyControl{
<...>
public void AddSelectedValueChagedHandler(SelectedValueChangedHandler h)
{
SelectedValueChanged -= h;
SelectedValueChanged +- h;
}
}
///-----------------------


Is there a standard way/pattern to make my life easier here? :) I think
i've seen somewhere that you can override -=/+- for an event or
something like that. I still would like to go with event instead of a
wrapper function as above.

Any ideas/comments are HIGHLY APPRECIATED!!!


Thank you in advance,
MuZZy
 
D

Dmytro Lapshyn [MVP]

Hi,

I recall there is a way to provide a custom implementation of the += and -=
operations for the event. The syntax, as I remember it, is something similar
to how a property is defined:

public event MyEvent
{
add
{
// The += implementation goes here.
}
remove
{
// The -= implementation goes here.
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top