What is event in C# | Event sample program


Program

using System;

namespace DelegatesAndEvents
{
    class EventExample01
    {
        delegate void delgMyWorks();

        event delgMyWorks MyEvents;

        public static void GetReady()
        {
            Console.WriteLine("Get up, fresh up and have break-fast");
        }
        public static void Go()
        {
            Console.WriteLine("Get (or) catch the vehicle to go office");
        }
        public static void Start()
        {
            Console.WriteLine("Swipe card (or) put signature and start                                                                   the work");
        }
        public static void Close()
        {
            Console.WriteLine("Submit the work, Sign out the system");
        }
        public static void Leave()
        {
            Console.WriteLine("Swipe card (or) put signature and leave to                                                                  home");
        }

        static void Main(string[] args)
        {
            EventExample01 obj1 = new EventExample01();

            Console.WriteLine("Time is 6 AM\n==============");
            //Registering methods into delegate instance1
            delgMyWorks morningWorks = new delgMyWorks(GetReady);
            morningWorks = morningWorks + Go + Start;
           
            //Initialize event with morning works delegate
            obj1.MyEvents = new delgMyWorks(morningWorks);
            //Triggering event
            obj1.MyEvents();

            Console.WriteLine("Time is 6 PM\n==============");
            //Registering methods into delegate instance2
            delgMyWorks eveningWorks = new delgMyWorks(Close);
            eveningWorks = eveningWorks + Leave;

            //Initialize event with evening works delegate
            obj1.MyEvents = new delgMyWorks(eveningWorks);
            //Triggering event
            obj1.MyEvents();

            Console.ReadKey();
        }
    }
}

Output

Time is 6 AM
==============
Get up, fresh up and have break-fast
Get (or) catch the vehicle to go office
Swipe card (or) put signature and start the work
Time is 6 PM
==============
Submit the work, Sign out the system
Swipe card (or) put signature and leave to home

No comments:

Post a Comment