Reader Level:
ARTICLE

Events and Delegates

Posted by Kunal Cheda Articles | C# Language July 26, 2001
Events in C# are based on delegates, the Originator defining one or more callback functions as delegates and the listening object then implements then.
  • 0
  • 0
  • 23510

Events in C# are based on delegates, the Originator defining one or more callback functions. A class that wants to use events defines callback functions as delegates and the listening object then implements then.

Source Code:

EventTest.cs

using
System;
public class MyEvt
{
public delegate void t(Object sender,MyArgs e);// declare a delegate
public event t tEvt; //delcares a event for the delegate
public void mm()
{ //function that will raise the callback
MyArgs r=new MyArgs();
tEvt(
this,r); //calling the client code
}
public MyEvt(){ }

//arguments for the callback
public class MyArgs:EventArgs
{
public MyArgs(){ }
}
public class MyEvtClient
{
MyEvt oo;
public MyEvtClient()
{
this .oo=new MyEvt();
this .oo.tEvt +=new MyEvt.t(oo_tt);
}
public static void Main (String [] args)
{
MyEvtClient cc=
new MyEvtClient();
cc.oo.mm();
}
//this code will be called from the server
public void oo_tt(object sender, MyArgs e)
{
Console.WriteLine("yes");
}
}

Save the File
as EventTest.cs
Compile C:\>csc EventTest.cs
run C:\>EventTest

COMMENT USING

Trending up