• Breaking News

    Tuesday 3 November 2015

    How to create Event program in C#

    Welcome to the C# tutorial. In this tutorial will see How to create Event program in C#.


    1. Defining the event : For defining the event you first need to declare a delegate

    Step a.

    public delegate void TimeToRise();
    

    Here , TimeToRise is the name of the delegate.

    Step b. Declare the event.

    public event TimeToRise RingAlarm;
    

    Here, RingAlarm is the name of the event.

    2. Subscribing to the event.

    Any class object can be the subscriber to the event.

    Here Student class is the subscriber.

    Student pd=new Student();
    //event Handler
    public void wakeup(){}
    RingAlarm = new TimeToRise(pd.wakeup);
    


    Complete Demo is Here:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        //Publisher Class
        class Event1
        {
            //step 1 declare the delegate 
            public delegate void TimeToRise();
    
            //declare a event variable using delegate
            public event TimeToRise RingAlarm;
            //create the method to raise the event
            public void onRingAlaram()
            {
                if (RingAlarm != null)
                    RingAlarm();
            }
        }
    
        //Subsciber class 
        class EventDemo2
        {
            //create a method to handle the event
            static void WakeUp()
            {
                Console.WriteLine("Wake Up.............");
    
    
            }
            public static void Main()
            {
                Event1 obj = new Event1(); // Publisher class object 
                obj.RingAlarm += WakeUp; // register the event with event handler
    
                obj.onRingAlaram();//raise an event
                Console.ReadLine();
    
            }
        }
    }
    

    Output:-


    No comments:

    Post a Comment