Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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?

That's what events are for. If you want to invoke it publicly you probably need delegates not events

Events gives encapsulation,

  1. It prevents other classes from assigning anything to it
  2. It prevents passing it as a parameter to methods
  3. It prevents assigning it to any variable
  4. It prevents calling it from another classes (not even derived classes have access to it)
  5. etc

public accessibility tells that it can be subscribed from anywhere, not invoked from anywhere.

the answer to your question is

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.

Invoking the event from outside doesn't makes sense therefore it is not allowed.

I think you should change your perspective on how events work. Other classes shouldn't "own" the event and trigger it. Classes which "listen" to the event by "subscribing" to it and do a certain action when this event occurs.

That's the way the language is defined - an event can only be fired by the owning class. If you must fire it from a different class, have the owning class define a public method that will fire the event:

public FireFooBarEvent (object sender, EventArgs args)
{
   if(FooBarEvent != null)
      FooBarEvent(sender, args);
}

And call this method from any class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top