Creating Delegates Only When Needed
In the two examples you've seen so far, the delegate is created whether or not it's ever used. That was fine in those examples because I knew that it would always be called. However, when defining your delegates, it's important to consider when to create them. Let's say, for example, that the creation of a particular delegate is time-consuming and not something you want to do gratuitously. In these situations in which you know the client won't typically call a given callback method, you can put off the creation of the delegate until it's actually needed by wrapping its instantiation in a property. To illustrate how to do this, a modification of the DBManager class follows that uses a read-only property-because only a getter method is present-to instantiate the delegate. The delegate will not be created until this property is referenced.
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 Delegate3App
{
public DBManager.EnumConnectionsCallback myCallback
{
get
{
return new DBManager.EnumConnectionsCallback
(ActiveConnectionsCallback);
}
}
public static void ActiveConnectionsCallback(DBConnection connection)
{
Console.WriteLine
("Callback method called for " + connection.name);
}
public static void Main()
{
Delegate3App app = new Delegate3App();
DBManager dbMgr = new DBManager();
dbMgr.AddConnections();
DBManager.EnumConnections(app.myCallback);
}
}