events in C#

An event allows a class or resource to notify the other classes or resource, when something required event occurs. The resource that raises the events is knows as publisher and the resource that handles the event is known as subscriber. In C# visual application we handle events like button clicked, combo box selection changed events etc. Similarly, we can raise our custom events when requires.

Overview of events

  • Publisher determines when to raise event, and subscriber determines how to handle the event.
  • An event can have multiple subscribers, and subscriber can handle multiple events.
  • An event that has no subscriber is never raised.
  • Events are typically used for user actions.
  • When an event has multiple subscriber than event handlers are invoked synchronously.
  •  Events are actually based on the EventHandler delegates.

Example of Events

public delegate void valueEntered(string value);
    class Program
        static void Main(string[] args)
            EventDemo ed = new EventDemo();
    public class EventDemo
        public static event valueEntered ve;
        public void startDemo()
            ve += new valueEntered(ValueEntered_Event);
            string str = Console.ReadLine();
        public void ValueEntered_Event(string value)
            Console.WriteLine("You Entered:" + value);

No comments:

Post a Comment