Monday 11 August 2014

Events in C#

Events:
Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriberclass. Events use the publisher-subscriber model.
publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.
subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.

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

namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
    
            Events e = new Events();
            e.call();     
        }

    }
} 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
    public delegate void EventHandler();
    class Events
    {
        public static event EventHandler _show;

        static void cat()
        {
            Console.WriteLine("cat");
        }
        static void dog()
        {
            Console.WriteLine("dog");
        }
        static void mouse()
        {
            Console.WriteLine("mouse");
        }
        public void call()
        {
            _show += new EventHandler(dog);
            _show += new EventHandler(cat);
            _show += new EventHandler(mouse);
            _show += new EventHandler(mouse);
            _show.Invoke();
        }
    }
}

Output :
Dog
Cat
mouse
mouse

No comments:

Post a Comment