An event is a member that enables the object to provide notifications. Events in C# are based on delegates, with the originator defining one or more callback functions. A callback function, as traditional Windows programmers will know, is a function where one piece of code defines and another implements. A class that wants to use events defines callback functions as delegates, and the listening object then implements them.

An event may include a set of attributes, a new modifier, a valid combination of the four access modifiers, and a valid combination of the static, virtual, override, and abstract modifiers.

Consider the following program:

Code:
using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

 

class Class1

{

static void Main(string[] args)

{

keyboard k = new keyboard ( ) ;

k.OnHit += new hit ( k.hit1 ) ;

k.OnHit += new hit ( k.hit2 ) ;

k.keyhit( ) ;

k.OnHit -= new hit ( k.hit1 ) ;

k.keyhit() ;

}

}

public delegate void hit( ) ;

public class keyboard

{

public event hit OnHit ;

public void keyhit( )

{

if ( OnHit != null )

{

OnHit() ;

}

}

public void hit1( )

{

Console.WriteLine ( "Key Hit1" ) ;

}

public void hit2( )

{

Console.WriteLine ( "Key Hit2" ) ;

}

}


We have declared a class called keyboard. In this class we added an event called OnHit. Two simple functions hit1( ) and hit2( ) are also added. The keyhit( ) method raises the OnHit event. The notion of raising an event is precisely equivalent to invoking the delegate represented by the event. Outside the class, the OnHit member can only be used on the left hand side of the += and -= operators, as in

k.OnHit += new hit ( k.hit1 ) ;

which actually appends a delegate to the invocation list of the OnHit event and -= removes a delegate from the list.. Hence as soon as we call k.keyhit( ) it raises the event and all functions are executed.