Interview question: Why can't events be invoked and their invocation list set from outside of the declaring class?
I found explanation to the first part of the question in this post Events Invocation
I assume the answer for the second part lies with security. Are there any other reasons considerations?
A keyword your interviewer may be looking for is encapsulation.
Events are only supposed to expose subscribe and unsubscribe operations to potential subscribers. Invocation is really the responsibility of the class that exposes the event.
Also keep in mind that public event EventHandler FooBar; is a short form of the following syntax
private EventHandler _fooBar;
public event EventHandler FooBar
{
add
{
_fooBar = (EventHandler)Delegate.Combine(_fooBar, value);
}
remove
{
_fooBar = (EventHandler)Delegate.Remove(_fooBar, value);
}
}
See Event Accessors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With