Raghav55
Raghav55

Reputation: 3135

Events Invocation

If a class declares a event then event can be fired only from that class. what is the reason for the restriction of the event invocation?

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication12
{
    delegate void Function();

    class EventHandling
    {
        public event Function fun;

        public void AddEvents(Function events)
        {
            fun += events;
        }

        public void Notify()
        {
            fun();
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            EventHandling aEvtHandler = new EventHandling();
            Function aFun = new Function(Display);
            aEvtHandler.AddEvents(aFun);
            aEvtHandler.Notify();
        }

        static void Display()
        {
            Console.WriteLine("in the display");
            Console.Read();
        }
    }
}

Upvotes: 0

Views: 142

Answers (1)

Roy Dictus
Roy Dictus

Reputation: 33139

Firing an event only makes sense from the class that defined it.

If I create a Bike class and that class contains an EngineStarted event, when is that event raised? When something happens that makes the engine start. So, the event being fired means that the instance of the class (a Bike object) reports to the outside world that the engine was started.

It makes no sense that another object would report to the world that the engine of a particular bike started, without the bike itself having reported that first.

Upvotes: 1

Related Questions