Features
- Delegate invoke instance method with parameter.
- Delegate invoke static method with parameter.
- Delegate multi-casting: delegate invoking more than one methods at once.
Instructions
Just compile and run the sample. The code is documented and is self-explanatory.
Concept/background
Delegate are just simple mechanism to re-route calls to functions/methods that it references. The idea is simple. Invoking delegate invokes the methods/functions that the delegate references. The question is, why delegate? Why not just invoke the function/method directly?
- The association between delegate and methods referenced by delegate is established in runtime - so, you get flexibility here.
- Multi-cast: That's to associate a few methods/functions to ONE delegate. Invoking one delegate fires off ALL
methods referenced by that one delegate all at once.
Code fragments
Here's your delegate
Methods referenced by SomeDelegate can be found in WorkerClass
public class WorkerClass
{
public int InstanceMethod(int nID, string sName) {...}
static public int StaticMethod(int nID, string sName) {...}
};
The only difference between these two methods is that "InstanceMethod" is an instance method,
that is, it must be invoked by an actual instance of WorkerClass. StaticMethod is a static member function -
invoke it by: WorkerClass.StaticMethod(10,"aaa");
What the function does?
Association between delegates and methods it references can be found in
main(...)
WorkerClass wr = new WorkerClass();
SomeDelegate d1 = new SomeDelegate(wr.InstanceMethod);
Console.WriteLine("Invoking delegate InstanceMethod, return={0}",
d1(5, "aaa") );
SomeDelegate d2 = new SomeDelegate(WorkerClass.StaticMethod);
Console.WriteLine("Invoking delegate StaticMethod, return={0}",
d2(5, "aaa") );
Console.WriteLine();
Console.WriteLine("Testing delegate multi-cast..");
SomeDelegate d3 = (SomeDelegate) Delegate.Combine(d1, d2);
Console.WriteLine("Invoking delegate(s) d1 AND d2 (multi-cast), return={0} ",
d3(5, "aaa") );
Conclusion
That's it. It's simple right?