Popular Posts

Oct 6, 2012

Events Programming in C#


Events
- An event is an automatic notification that some action  has occurred.
-  An event might be a button push, a menu selection, and so forth. In short, something
happens and you must respond to it with an event handler. 
-  Event is a member of a class and are declared using the event keyword which has the
form-


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

namespace Final_events
{
    // Declare a delegate for an event.  
    delegate void MyEventHandler();

    // Declare an event class. 
    class MyEvent
    {
        public event MyEventHandler SomeEvent; 
 
          // This is called to fire the event. 
          public void OnSomeEvent() { 
            if(SomeEvent != null) 
              SomeEvent(); 
          } 
        }
   

    

    class Program
    {
        // An event handler. 
        static void handler()
        {
            Console.WriteLine("Event occurred");
        }

        static void Main(string[] args)
        {
            MyEvent evt = new MyEvent(); 
 
            // Add handler() to the event list. 
            evt.SomeEvent += handler; 
         
            // Fire the event. 
            evt.OnSomeEvent();

            Console.ReadKey();

        }
    }
}

No comments:

Post a Comment