Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 19-12-2008
Member
 
Join Date: Aug 2008
Posts: 88
Events in C sharp

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.
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Events in C sharp"
Thread Thread Starter Forum Replies Last Post
Sharp 007SH Hybrid An 3D Clamshell Android Phone by Sharp jackalz Web News & Trends 3 22-05-2011 07:28 AM
All day events one day out Steadfast Portable Devices 4 13-10-2010 11:22 AM
Why we use Events in JavaScript? Samarth Software Development 5 30-01-2010 09:15 PM
Keyboard events in c + + Zool Software Development 3 03-10-2009 09:17 AM
jQuery and several events AZUL Software Development 3 28-09-2009 04:19 PM


All times are GMT +5.5. The time now is 09:41 PM.