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.
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.
by
updated