C Sharp

Defining Delegates as Static Members

Because it's kind of clunky that the client has to instantiate the delegate each time the delegate is to be used, C# allows you to define as a static class member the method that will be used in the creation of the delegate. Following is the example from the previous section, changed to use that format. Note that the delegate is now defined as a static member of the class named myCallback, and also note that this member can be used in the Main method without the need for the client to instantiate the delegate.

using System;
class DBConnection
{
    public DBConnection(string name)
    {
        this.name = name;
    }
    protected string Name;
    public string name
    {
        get
        {
            return this.Name;
        }
        set
        {
            this.Name = value;
        }
    }
}
class DBManager
{
    static DBConnection[] activeConnections;
    public void AddConnections()
    {
        activeConnections = new DBConnection[5];
        for (int i = 0; i < 5; i++)
        {
            activeConnections[i] = new
DBConnection("DBConnection " + (i + 1));
        }
    }
    public delegate void EnumConnectionsCallback(DBConnection connection);
    public static void EnumConnections(EnumConnectionsCallback callback)
    {
        foreach (DBConnection connection in activeConnections)
        {
            callback(connection);
        }
    }
}
class Delegate2App
{
    public static DBManager.EnumConnectionsCallback myCallback =
        new DBManager.EnumConnectionsCallback(ActiveConnectionsCallback);
    public static void ActiveConnectionsCallback(DBConnection connection)
    {
        Console.WriteLine ("Callback method called for " +
                           connection.name);
    }
    public static void Main()
    {
        DBManager dbMgr = new DBManager();
        dbMgr.AddConnections();
        DBManager.EnumConnections(myCallback);
    }
}
NOTE
Because the standard naming convention for delegates is to append the word Callback to the method that takes the delegate as its argument, it's easy to mistakenly use the method name instead of the delegate name. In that case, you'll get a somewhat misleading compile-time error that states that you've denoted a method where a class was expected. If you get this error, remember that the actual problem is that you've specified a method instead of a delegate.