Question regarding event handlers and delegates

B

Bruce C. Miller

So, say I have an instance of a .Net object with a collection of
events. It is possible to get at these events and look at them with
various relection-type properties. However, would it be possible to
take another instance of the same type of .Net object, grab all of the
event handlers off of the old object, and stick them onto the new
one?

That is, do have access to these event handler methods (which are
delegates) from just looking at an instantiation of the object, and
can I pull them off and add them as event handlers on another object
of the same type?
 
J

Jon Skeet [C# MVP]

Bruce C. Miller said:
So, say I have an instance of a .Net object with a collection of
events. It is possible to get at these events and look at them with
various relection-type properties. However, would it be possible to
take another instance of the same type of .Net object, grab all of the
event handlers off of the old object, and stick them onto the new
one?

Not necessarily.
That is, do have access to these event handler methods (which are
delegates) from just looking at an instantiation of the object, and
can I pull them off and add them as event handlers on another object
of the same type?

No - because events are like properties. Just because a class has a
property doesn't mean that property is directly backed by a field, and
the same is true for an event. An event has an "adder" and a "remover"
but they could store the delegate passed into them in a map, or
something like that.

Now *typically* they just use a field - but it's not a reliable way of
doing things.
 
P

Pavel Minaev

So, say I have an instance of a .Net object with a collection of
events. It is possible to get at these events and look at them with
various relection-type properties. However, would it be possible to
take another instance of the same type of .Net object, grab all of the
event handlers off of the old object, and stick them onto the new
one?

That is, do have access to these event handler methods (which are
delegates) from just looking at an instantiation of the object, and
can I pull them off and add them as event handlers on another object
of the same type?

No. The whole point of having events as a distinct entity to
properties/fields of delegate type is encapsulation - only object
itself can inspect the list of event handlers (a particular case of
this is calling all the handlers), and objects of other classes can
only subscribe and unsubscribe.
 

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