Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why public event cannot be invoked outside directly?

Consider we have a class with event declared:

public class FooBar
{
    public event EventHandler FooBarEvent;
}

Despite of "publicness" of the event, we cannot call FooBarEvent.Invoke from outside.

This is overcame by modyfing a class with the following approach:

public class FooBar
{
    public event EventHandler FooBarEvent;

    public void RaiseFooBarEvent(object sender, EventArgs eventArguments)
    {
        FooBarEvent.Invoke(sender, eventArguments);
    }
}

Why accessing public events outside is limited by adding and removing listeners only?

like image 642
Ilya Tereschuk Avatar asked Jan 21 '14 12:01

Ilya Tereschuk


People also ask

How do I invoke an event in C#?

Events in C# are simple things on the face of it. You create an event signature using a delegate type and mark it with the event keyword. External code can register to receive events. When specific things occur within your class, you can easily trigger the event, notifying all external listeners.

What is the use of delegates and events in c#?

Delegates are the library class in System namespace. These are the type-safe pointer of any method. Delegates are mainly used in implementing the call-back methods and events. Delegates can be chained together as two or more methods can be called on a single event.

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.


2 Answers

Defining a public event merely gives consumers the ability to subscribe and unsubscribe from it. The ability to raise the event is limited to the type hierarchy which declares the event.

Allowing all subscribers to also be able to raise the event would be a bit chaotic. Imagine for example I had a TextBox class which had a Focused event. If any old consumer could raise the event then the Focused event could easily fire when the TextBox class wasn't actually focused. This would make it nearly impossible to maintain any type of invariant during an event.

like image 171
JaredPar Avatar answered Sep 19 '22 19:09

JaredPar


Personally I think this is done to properly convey the design principles behind the whole events architecture.

The purpose of an event is to notify a listener of said event occurring in a given object.

What's the point of raising events of classes that don't belong to you?

like image 23
Alex Avatar answered Sep 19 '22 19:09

Alex