Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't events be invoked or their invocation list set from outside of the declaring class

Tags:

c#

.net

events

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?

like image 492
Tamas Pataky Avatar asked Jan 29 '26 02:01

Tamas Pataky


1 Answers

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

like image 141
Brandon Cuff Avatar answered Jan 30 '26 15:01

Brandon Cuff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!