• Have Any Question?
  • contact@eitworld.com

csharp events





C# Events

 

  • Event is a very important feature of the C#.
  • Events are the certain actions that happen during the execution of program for which the application wishes to be notified about, so it can respond.
  • An event can be a mouse click, keystroke or alarm.

Declaration of Events

 

  • Events are member of class and declared using the event keyword.
  • The basic structure of declaration of an event is given below:
event event-delegate event-name

  • The class that contains the class known as publisher class and the class that accepts the event is called subscriber class.
  • Subscriber class provides an event handler to handle the event.

Here event-delegate is the name of delegate used to support the event and event-name is the name of the specific event being declared.

 

Example

 

using System;
delegate void MyEventHandler();//Create a delegate for the event.
// Declare a class that contains an event.
class MyEvent {
public event MyEventHandler SomeEvent;//declare an event
public void Fire()
{
if(SomeEvent != null)
SomeEvent();//Fire the event.
}
}
class EventDemo
{
static void Handler()//An event handler.
{
Console.WriteLine(“Event occurred”);
}
static void Main()
{
MyEvent evt = new MyEvent();//Create event instance.
evt.SomeEvent += Handler;// Add Handler() to the event list.
evt.Fire();// Generate the event.
Console.ReadLine();
}
}

The Output of the above program will be as follows:

 

Output

 

Event occured



Real Time Web Analytics