They usually don't teach you in most textbooks I've seen that
delegates can be used to call class methods from classes that are
'unaware' of the delegate, so long as the class has the same signature
for the method (i.e., as below, int Square (int)).
Here is an example to show that feature. Note class "UnAwareCla ss"
has its methods Square and Cuber called by a class DelegateClass.
This is because these methods in UnAwareClass have the same signature
and so they can be called by DelegateClass, without the keyword
'delegate' ever appearing in UnAwareClass.
Note the keyword 'static' has to be used as below, even though
UnAwareClass itself is not static, though there is a way to use
delegates with non-static functions (however I don't see the need to
do so).
Pretty cool if you ask me--like a functor in C++.
RL
//Delegate model showing how another class (“UnAwareClass” ) does not
even have to be aware of the delegate and still be called and
employed.
///
///////
// OUTPUT (takes the square of a number, here 11, and the cube, to
give 121 and 1331)
...now for external use of delegates from two classes...
Square 11 is: 121
!Cube 11 is: 1331
Press any key to continue . . .
///////
using System;
using System.Collecti ons.Generic;
using System.Text;
namespace EventDelegates
{
class Program
{
static void Main(string[] args)
{
UnAwareClass myUnAwareClass = new UnAwareClass();
// now to access delegate from another class
Console.WriteLi ne("...now for external use of delegates from two
classes...");
DelegateClass.P ublicHigherPowe r2 sQr = new
DelegateClass.P ublicHigherPowe r2(UnAwareClass .Square); //!!! Note: how
called: UnAwareClass.Sq uare
DelegateClass myDelegateClass = new DelegateClass() ; //
apparently no ill effects if follows rather than preceeds previous
line
int ji2 = myDelegateClass .DoOp(sQr, 11);
Console.WriteLi ne("Square 11 is: {0}", ji2);
DelegateClass.P ublicHigherPowe r2 Cub2 = new
DelegateClass.P ublicHigherPowe r2(UnAwareClass .Cuber);
//!!! note: how called: UnAwareClass.Cu ber
ji2 = myDelegateClass .DoOp(Cub2, 11);
Console.WriteLi ne(" !Cube 11 is: {0}", ji2);
// !!!Note significance: 'delegate' keyword NEVER APPEARS in class
UnAwareClass (!)
}
}
}
////////////
using System;
using System.Collecti ons.Generic;
using System.Text;
namespace EventDelegates
{
class UnAwareClass
{
//!! in this version, 'delegate' keyword does not appear in
this class (UnAwareClass) but only DelegateClass class
int[] values;
int i;
public UnAwareClass()
{
values = new int[] { 1, 2, 3 }; //not used
i = 22333; //not used
}
public static int Square(int x)
{
return x * x;
}
public static int Cuber(int y)
{
return y * y * y;
}
}
class DelegateClass
{
public delegate int PublicHigherPow er2(int x); //delegate to
be used externally (keyword delegate must of course be declared here)
int j;
public DelegateClass()
{
j = 0;
}
public int DoOp(PublicHigh erPower2 ar, int x) //note format
{
return ar(x);
}
}
}