Events:
Microsoft Launches events for Developers, to make them aware about the features of New or existing products. Microsoft Notifies the Developers about the Event by Email or other Advertisement Options. So in this case, Microsoft is a Publisher Who launches " raises " an Event and Notifies the Developers about it and developers are the Subscribers of the event and attend " Handle " the event.
Events in C# follow the similar concept. An event has a Publisher, subscriber, notification and a Handler. Generally, UI controls use events extensively. For Example, the button control in a windows form has multiple events such as click, mouse-over etc. A custom Class can also have an event to Notify other Subscriber classes about something that has happened or is going to happen.
Using Delegates with Events:
The Events are declared and Raised in a class and Associated with the event handlers using Delegates within the Class. The class containing the event is used to publish the event. This is called the Publisher class. some other class that accepts this event is called the Subscriber class. Events Use the Publisher and Subscriber Model.
Publisher:
Publisher is an Object that contains the Definition of the Event and the Delegate. The Event-Delegate association is also defined in this Object. a Publisher class object invokes the event and it is notified to other objects.
Subscriber:
Subscriber is an object that accepts and provides an event handler. the Delegate in the publisher class invokes the Method ( Event Handler ) of the subscriber class.
Events Declaration:
An Event is Nothing but an Encapsulated Delegates . As we have learned in Our Previous Tutorial, a delegate is a reference type data type. so to declare an event inside a class, first we need to declare an Delegate type for the event, as show below:
//Declare an Delegate type for the Event:
Access_Modifier delegate Return_Type delegate-name( Parameters)
After Declaring an Delegate type, we can declare an event using event keyword as shown below.
//Declare an Event using delegate:
Access_Modifier event delegate-name Event_Name;
Let's have an simple example to understand how we declare and use event in C#.
/*Example - Events - InfoBrother*/
using System;
namespace EventHandler
{
//Delegate declare:
public delegate string Message(string msg);
class Program
{
//declare Event of type Delegate:
public event Message NewMessage;
public Program() //constructor:
{
//subscribe to NewMessage event:
this.NewMessage += new Message(this.readMsg);
}
//Event Handler:
public string readMsg(string from)
{
return "You Got a New Message from " + from;
}
static void Main(string[] args)
{
Program obj = new Program(); //Object:
string showMessage = obj.NewMessage("InfoBrother."); //calling method:
Console.WriteLine(showMessage);
Console.ReadKey();
}
}
}
Events:
You Got a New Message from InfoBrother.