Wiring Up An Event

G

Guest

I have several instances where I wire up an event handler like this:

// Instantiate object
childClass parentObject = new childClass();

// Wire up event
parentObject.SomeChildEvent += new EventHandler(ParentEventHandler);



What I'm wondering though is if there's a way with dotNet 1.1 for me to
somehow pass the necessary information contained in the 2nd line of code to a
separate class and have the wiring occur there? This would mean that if the
event is fired it'll still be handled by 'ParentEventHandler' in the parent
class.

I tried experimenting with delegates to do this but just couldn't figure it
out. Is it possible to do?
 
J

Jon Skeet [C# MVP]

Robert W. said:
I have several instances where I wire up an event handler like this:

// Instantiate object
childClass parentObject = new childClass();

// Wire up event
parentObject.SomeChildEvent += new EventHandler(ParentEventHandler);

What I'm wondering though is if there's a way with dotNet 1.1 for me to
somehow pass the necessary information contained in the 2nd line of code to a
separate class and have the wiring occur there?

Well, you can pass the delegate through as a parameter (of type
EventHandler) very easily.

You can't easily pass the event itself though - the other class would
need to know that it's the SomeChildEvent that needs wiring up.
 
S

Scott Roberts

Robert W. said:
I have several instances where I wire up an event handler like this:

// Instantiate object
childClass parentObject = new childClass();

// Wire up event
parentObject.SomeChildEvent += new EventHandler(ParentEventHandler);



What I'm wondering though is if there's a way with dotNet 1.1 for me to
somehow pass the necessary information contained in the 2nd line of code to a
separate class and have the wiring occur there? This would mean that if the
event is fired it'll still be handled by 'ParentEventHandler' in the parent
class.

// Instantiate object
childClass parentObject = new childClass();

// Create event handler.
EventHandler myHandler = new EventHandler(ParentEventHandler);

// Call some method to wire up event handler to object.
WireUpSomeChildEvent(parentObject,myHandler);

// Method to wire up an event handler on an object.
public void WireUpSomeChildEvent(childClass aObject, EventHandler aHandler)
{
aObject.SomeChildEvent += aHandler;
}
 
G

Guest

Jon, Scott,

Thank you! And Scott, your sample code was excellent!

You know, just when I think I'm becoming more proficient I seem to run into
these little things that just baffle me. And then I see such simple, elegant
solutions and it all becomes clear again. Oh well, one day I'll have this
all figured out!! :)
 

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