Monday 1 February 2016

What is event in c# ? How to create it ?



An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).
Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.
Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing. Recall that a delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.

Example:-



using System;

    class MyClass
    {
        public delegate void MyDelegate(string message);
        public event MyDelegate MyEvent;

        //this method will be used to raise the event.
        public void RaiseEvent(string message)
        {
            if (MyEvent != null)
                MyEvent(message);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);

            Console.WriteLine("Please enter number\n");
            string msg = Console.ReadLine();

            //here is we raise the event.
            myClass1.RaiseEvent(msg);
            Console.Read();
        }
        //this method will be executed when the event raised.
        static void myClass1_MyEvent(string message)
        {
            Console.WriteLine("Your Message is: {0}", message);
        }
    }




Output:-













No comments:

Post a Comment