Delegates and Events in C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. Although delegates have other uses, the discussion here focuses on the event-handling functionality of delegates.

Events in C# are handled by delegates, which serve as a mechanism that defines one or more callback functions to process events. An event is a message sent by an object to signal the occurrence of an action. The action could arise from user interaction, such as a mouse click, or could be triggered by some other program logic. The object that triggers the event is called the event sender. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will handle the events it raises. It merely functions as an intermediary or pointer-like mechanism between the source and the receiver, as illustrated in Listing 5.47. The .NET framework defines a special type delegate that serves as a function pointer.

Listing 5.47: DelegateEvent.cs, Delegates and Events Example


using
System;
public
class MyEvt
{
    public delegate void t(Object sender, MyArgs e);

    // declare a delegate

    public event t tEvt; //declares an 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");
        Console.ReadLine();
    }
}


fig-5.10.gif

Figure 5.10: Screen Output Generated from Listing 5.47

Conclusion

Hope this article would have helped you in understanding Delegates and Events in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Similar Articles
C# Corner
C# Corner started as an online community for software developers in 1999.