passing an event as a parameter

  • Thread starter Thread starter Vadim Berezniker
  • Start date Start date
V

Vadim Berezniker

Let's say I have a base class BaseClass that defines an event
'ValueChanged' and then I have inherited classes that have specific
'SomeValueChanged', 'SomeOtherValueChanged' events.
I want to have 'ValueChanged' fired every time one of the value change
event fires in the subclasses. My first thought was to have a method in
the base class that would take a reference to an event as a parameter
and then connect that event with a handler that would then fire the
ValueChanged event. Instead, now I connect the event in the subclasses
which felt like a less "cleaner" way to accomplish this. I wanted the
base class to actually connect the event to its handler. Is there any
way to achieve this?
 
Hi Vadim,

For what you are doing, it sounds like a delegate would be the most
appropriate choice. Events are essentially delegates that are type members
with the additional protection of preventing invocation from outside the
type and assignment. Delegates can be passed as parameters, may be
multicast (have multiple handlers), and can be invoked from anywhere as
specified by their access modifier.

Joe
 
public class BaseClass
{
public event ValueChanged;

protected void OnValueChanged(BaseClass sender)
{
if (ValueChanged != null)
{
ValueChanged(sender, System.EventArgs.Empty);
}
}
}

public class DerivedClass : BaseClass
{
public event SomeValueChanged;

protected void OnSomeValueChanged()
{
if (SomeValueChanged != null)
{
SomeValueChanged(this, System.EventArgs.Empty);
}
base.OnValueChanged(this);
}
}

Is this the effect you wanted? The ValueChanged event from the base
class now fires every time the SomeValueChanged event fires in the
child class.
 
By the way... in my sample code OnValueChanged() does not need to take
an argument. You can just always pass this to ValueChanged:

ValueChanged(this, System.EventArgs.Empty);

When called from the child class, "this" will be the child class
object. D'oh! It's early. I'm not awake yet. :)
 
Joe said:
Hi Vadim,

For what you are doing, it sounds like a delegate would be the most
appropriate choice. Events are essentially delegates that are type members
with the additional protection of preventing invocation from outside the
type and assignment. Delegates can be passed as parameters, may be
multicast (have multiple handlers), and can be invoked from anywhere as
specified by their access modifier.

Joe

Thanks. I think that's the proper solution.
Don't know why I didn't think of that =)
 

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

Back
Top