Events in C#

Now we are going to learn about events in the C#.
  • 2160

Introduction

The event is a method in C#. That's provide a notification where clients can executed the code for every event. Other thing is that event is provide a notification to a class that something is very interested happening somewhere.

The most popular use of event is in Graphical user interface. In GUI whenever a user use something for the control it may be the event for when a user click on a button then interface have a event.

The event is a building block for creating classes. After that it is used for create large number of program. We can say that events are the members of the class that lift up them every class. Sometimes classes do those work that become a events when a class send a message for a event and event send for a application and application executed them then it will become a event handlers.

Program for Event is given below:

namespace Events
{
public
class Class
{
public
delegate void MyDelegate(string message);
    public
event MyDelegate MyEvent;
         public
void RaiseEvent(string message)
            {
        if
(MyEvent != null)
               MyEvent(message);
             }
  }
    
class Program
           
{
       static
void Main(string[] args)
            {
       Class Class1 = new Class();
             Class1.MyEvent += new Class.MyDelegate(Class1_MyEvent);
                Console
.WriteLine("Please enter a message\n");
                     string
msg = Console.ReadLine();
                          Class1.RaiseEvent(msg);
                               Console
.Read();
              }
            static
void Class1_MyEvent(string message)
                    {
                Console
.WriteLine("Your Message is: {0}", message);
                    }
              }
   }

Output

event.jpg

 

© 2013 dotNetheaven. All rights reserved.